icon_util.cc revision a93a17c8d99d686bd4a1511e5504e5e6cc9fcadf
1// Copyright (c) 2012 The Chromium Authors. All rights reserved. 2// Use of this source code is governed by a BSD-style license that can be 3// found in the LICENSE file. 4 5#include "ui/gfx/icon_util.h" 6 7#include "base/file_util.h" 8#include "base/files/important_file_writer.h" 9#include "base/logging.h" 10#include "base/memory/scoped_ptr.h" 11#include "base/win/resource_util.h" 12#include "base/win/scoped_gdi_object.h" 13#include "base/win/scoped_handle.h" 14#include "base/win/scoped_hdc.h" 15#include "skia/ext/image_operations.h" 16#include "third_party/skia/include/core/SkBitmap.h" 17#include "ui/gfx/gdi_util.h" 18#include "ui/gfx/image/image.h" 19#include "ui/gfx/image/image_family.h" 20#include "ui/gfx/size.h" 21 22namespace { 23 24struct ScopedICONINFO : ICONINFO { 25 ScopedICONINFO() { 26 hbmColor = NULL; 27 hbmMask = NULL; 28 } 29 30 ~ScopedICONINFO() { 31 if (hbmColor) 32 ::DeleteObject(hbmColor); 33 if (hbmMask) 34 ::DeleteObject(hbmMask); 35 } 36}; 37 38// Creates a new ImageFamily, |resized_image_family|, based on the images in 39// |image_family|, but containing images of specific dimensions desirable for 40// Windows icons. For each desired image dimension, it chooses the most 41// appropriate image for that size, and resizes it to the desired size. 42// Returns true on success, false on failure. Failure can occur if 43// |image_family| is empty, all images in the family have size 0x0, or an image 44// has no allocated pixel data. 45// |resized_image_family| must be empty. 46bool BuildResizedImageFamily(const gfx::ImageFamily& image_family, 47 gfx::ImageFamily* resized_image_family) { 48 DCHECK(resized_image_family); 49 DCHECK(resized_image_family->empty()); 50 51 for (size_t i = 0; i < IconUtil::kNumIconDimensions; ++i) { 52 int dimension = IconUtil::kIconDimensions[i]; 53 gfx::Size size(dimension, dimension); 54 const gfx::Image* best = image_family.GetBest(size); 55 if (!best || best->IsEmpty()) { 56 // Either |image_family| is empty, or all images have size 0x0. 57 return false; 58 } 59 60 // Optimize for the "Large icons" view in Windows Vista+. This view displays 61 // icons at full size if only if there is a 256x256 (kLargeIconSize) image 62 // in the .ico file. Otherwise, it shrinks icons to 48x48 (kMediumIconSize). 63 if (dimension > IconUtil::kMediumIconSize && 64 best->Width() <= IconUtil::kMediumIconSize && 65 best->Height() <= IconUtil::kMediumIconSize) { 66 // There is no source icon larger than 48x48, so do not create any 67 // images larger than 48x48. kIconDimensions is sorted in ascending 68 // order, so it is safe to break here. 69 break; 70 } 71 72 if (best->Size() == size) { 73 resized_image_family->Add(*best); 74 } else { 75 // There is no |dimension|x|dimension| source image. 76 // Resize this one to the desired size, and insert it. 77 SkBitmap best_bitmap = best->AsBitmap(); 78 // If a gfx::Image was created from a SkBitmap with no allocated pixels, 79 // AsBitmap will return a null bitmap instead. This bitmap will have no 80 // config and a size of 0x0. Check this and fail early, to avoid having 81 // 0x0-sized bitmaps in our resized image family. 82 if (best_bitmap.config() == SkBitmap::kNo_Config) 83 return false; 84 SkBitmap resized_bitmap = skia::ImageOperations::Resize( 85 best_bitmap, skia::ImageOperations::RESIZE_LANCZOS3, 86 dimension, dimension); 87 resized_image_family->Add(gfx::Image::CreateFrom1xBitmap(resized_bitmap)); 88 } 89 } 90 return true; 91} 92 93// Creates a set of bitmaps from an image family. 94// All images smaller than 256x256 are converted to SkBitmaps, and inserted into 95// |bitmaps| in order of aspect ratio (thinnest to widest), and then ascending 96// size order. If an image of exactly 256x256 is specified, it is converted into 97// PNG format and stored in |png_bytes|. Images with width or height larger than 98// 256 are ignored. 99// |bitmaps| must be an empty vector, and not NULL. 100// Returns true on success, false on failure. This fails if any image in 101// |image_family| is not a 32-bit ARGB image, or is otherwise invalid. 102bool ConvertImageFamilyToBitmaps( 103 const gfx::ImageFamily& image_family, 104 std::vector<SkBitmap>* bitmaps, 105 scoped_refptr<base::RefCountedMemory>* png_bytes) { 106 DCHECK(bitmaps != NULL); 107 DCHECK(bitmaps->empty()); 108 109 for (gfx::ImageFamily::const_iterator it = image_family.begin(); 110 it != image_family.end(); ++it) { 111 const gfx::Image& image = *it; 112 113 // All images should have one of the kIconDimensions sizes. 114 DCHECK_GT(image.Width(), 0); 115 DCHECK_LE(image.Width(), IconUtil::kLargeIconSize); 116 DCHECK_GT(image.Height(), 0); 117 DCHECK_LE(image.Height(), IconUtil::kLargeIconSize); 118 119 SkBitmap bitmap = image.AsBitmap(); 120 121 // Only 32 bit ARGB bitmaps are supported. We also make sure the bitmap has 122 // been properly initialized. 123 SkAutoLockPixels bitmap_lock(bitmap); 124 if ((bitmap.config() != SkBitmap::kARGB_8888_Config) || 125 (bitmap.getPixels() == NULL)) { 126 return false; 127 } 128 129 // Special case: Icons exactly 256x256 are stored in PNG format. 130 if (image.Width() == IconUtil::kLargeIconSize && 131 image.Height() == IconUtil::kLargeIconSize) { 132 *png_bytes = image.As1xPNGBytes(); 133 } else { 134 bitmaps->push_back(bitmap); 135 } 136 } 137 138 return true; 139} 140 141} // namespace 142 143// The icon images appear in the icon file in same order in which their 144// corresponding dimensions appear in this array, so it is important to keep 145// this array sorted. Also note that the maximum icon image size we can handle 146// is 256 by 256. See: 147// http://msdn.microsoft.com/en-us/library/windows/desktop/aa511280.aspx#size 148const int IconUtil::kIconDimensions[] = { 149 8, // Recommended by the MSDN as a nice to have icon size. 150 10, // Used by the Shell (e.g. for shortcuts). 151 14, // Recommended by the MSDN as a nice to have icon size. 152 16, // Toolbar, Application and Shell icon sizes. 153 22, // Recommended by the MSDN as a nice to have icon size. 154 24, // Used by the Shell (e.g. for shortcuts). 155 32, // Toolbar, Dialog and Wizard icon size. 156 40, // Quick Launch. 157 48, // Alt+Tab icon size. 158 64, // Recommended by the MSDN as a nice to have icon size. 159 96, // Recommended by the MSDN as a nice to have icon size. 160 128, // Used by the Shell (e.g. for shortcuts). 161 256 // Used by Vista onwards for large icons. 162}; 163 164const size_t IconUtil::kNumIconDimensions = arraysize(kIconDimensions); 165const size_t IconUtil::kNumIconDimensionsUpToMediumSize = 9; 166 167HICON IconUtil::CreateHICONFromSkBitmap(const SkBitmap& bitmap) { 168 // Only 32 bit ARGB bitmaps are supported. We also try to perform as many 169 // validations as we can on the bitmap. 170 SkAutoLockPixels bitmap_lock(bitmap); 171 if ((bitmap.config() != SkBitmap::kARGB_8888_Config) || 172 (bitmap.width() <= 0) || (bitmap.height() <= 0) || 173 (bitmap.getPixels() == NULL)) 174 return NULL; 175 176 // We start by creating a DIB which we'll use later on in order to create 177 // the HICON. We use BITMAPV5HEADER since the bitmap we are about to convert 178 // may contain an alpha channel and the V5 header allows us to specify the 179 // alpha mask for the DIB. 180 BITMAPV5HEADER bitmap_header; 181 InitializeBitmapHeader(&bitmap_header, bitmap.width(), bitmap.height()); 182 void* bits; 183 HDC hdc = ::GetDC(NULL); 184 HBITMAP dib; 185 dib = ::CreateDIBSection(hdc, reinterpret_cast<BITMAPINFO*>(&bitmap_header), 186 DIB_RGB_COLORS, &bits, NULL, 0); 187 DCHECK(dib); 188 ::ReleaseDC(NULL, hdc); 189 memcpy(bits, bitmap.getPixels(), bitmap.width() * bitmap.height() * 4); 190 191 // Icons are generally created using an AND and XOR masks where the AND 192 // specifies boolean transparency (the pixel is either opaque or 193 // transparent) and the XOR mask contains the actual image pixels. If the XOR 194 // mask bitmap has an alpha channel, the AND monochrome bitmap won't 195 // actually be used for computing the pixel transparency. Even though all our 196 // bitmap has an alpha channel, Windows might not agree when all alpha values 197 // are zero. So the monochrome bitmap is created with all pixels transparent 198 // for this case. Otherwise, it is created with all pixels opaque. 199 bool bitmap_has_alpha_channel = PixelsHaveAlpha( 200 static_cast<const uint32*>(bitmap.getPixels()), 201 bitmap.width() * bitmap.height()); 202 203 scoped_ptr<uint8[]> mask_bits; 204 if (!bitmap_has_alpha_channel) { 205 // Bytes per line with paddings to make it word alignment. 206 size_t bytes_per_line = (bitmap.width() + 0xF) / 16 * 2; 207 size_t mask_bits_size = bytes_per_line * bitmap.height(); 208 209 mask_bits.reset(new uint8[mask_bits_size]); 210 DCHECK(mask_bits.get()); 211 212 // Make all pixels transparent. 213 memset(mask_bits.get(), 0xFF, mask_bits_size); 214 } 215 216 HBITMAP mono_bitmap = ::CreateBitmap(bitmap.width(), bitmap.height(), 1, 1, 217 reinterpret_cast<LPVOID>(mask_bits.get())); 218 DCHECK(mono_bitmap); 219 220 ICONINFO icon_info; 221 icon_info.fIcon = TRUE; 222 icon_info.xHotspot = 0; 223 icon_info.yHotspot = 0; 224 icon_info.hbmMask = mono_bitmap; 225 icon_info.hbmColor = dib; 226 HICON icon = ::CreateIconIndirect(&icon_info); 227 ::DeleteObject(dib); 228 ::DeleteObject(mono_bitmap); 229 return icon; 230} 231 232SkBitmap* IconUtil::CreateSkBitmapFromHICON(HICON icon, const gfx::Size& s) { 233 // We start with validating parameters. 234 if (!icon || s.IsEmpty()) 235 return NULL; 236 ScopedICONINFO icon_info; 237 if (!::GetIconInfo(icon, &icon_info)) 238 return NULL; 239 if (!icon_info.fIcon) 240 return NULL; 241 return new SkBitmap(CreateSkBitmapFromHICONHelper(icon, s)); 242} 243 244scoped_ptr<SkBitmap> IconUtil::CreateSkBitmapFromIconResource(HMODULE module, 245 int resource_id, 246 int size) { 247 DCHECK_LE(size, kLargeIconSize); 248 249 // For everything except the Vista+ 256x256 icons, use |LoadImage()|. 250 if (size != kLargeIconSize) { 251 HICON icon_handle = 252 static_cast<HICON>(LoadImage(module, MAKEINTRESOURCE(resource_id), 253 IMAGE_ICON, size, size, 254 LR_DEFAULTCOLOR | LR_DEFAULTSIZE)); 255 scoped_ptr<SkBitmap> bitmap(IconUtil::CreateSkBitmapFromHICON(icon_handle)); 256 DestroyIcon(icon_handle); 257 return bitmap.Pass(); 258 } 259 260 // For Vista+ 256x256 PNG icons, read the resource directly and find 261 // the corresponding icon entry to get its PNG bytes. 262 void* icon_dir_data = NULL; 263 size_t icon_dir_size = 0; 264 if (!base::win::GetResourceFromModule(module, resource_id, RT_GROUP_ICON, 265 &icon_dir_data, &icon_dir_size)) { 266 return scoped_ptr<SkBitmap>(); 267 } 268 DCHECK(icon_dir_data); 269 DCHECK_GE(icon_dir_size, sizeof(GRPICONDIR)); 270 271 const GRPICONDIR* icon_dir = 272 reinterpret_cast<const GRPICONDIR*>(icon_dir_data); 273 const GRPICONDIRENTRY* large_icon_entry = NULL; 274 for (size_t i = 0; i < icon_dir->idCount; ++i) { 275 const GRPICONDIRENTRY* entry = &icon_dir->idEntries[i]; 276 // 256x256 icons are stored with width and height set to 0. 277 // See: http://en.wikipedia.org/wiki/ICO_(file_format) 278 if (entry->bWidth == 0 && entry->bHeight == 0) { 279 large_icon_entry = entry; 280 break; 281 } 282 } 283 if (!large_icon_entry) 284 return scoped_ptr<SkBitmap>(); 285 286 void* png_data = NULL; 287 size_t png_size = 0; 288 if (!base::win::GetResourceFromModule(module, large_icon_entry->nID, RT_ICON, 289 &png_data, &png_size)) { 290 return scoped_ptr<SkBitmap>(); 291 } 292 DCHECK(png_data); 293 DCHECK_EQ(png_size, large_icon_entry->dwBytesInRes); 294 295 const unsigned char* png_bytes = 296 reinterpret_cast<const unsigned char*>(png_data); 297 gfx::Image image = gfx::Image::CreateFrom1xPNGBytes(png_bytes, png_size); 298 return scoped_ptr<SkBitmap>(new SkBitmap(image.AsBitmap())); 299} 300 301SkBitmap* IconUtil::CreateSkBitmapFromHICON(HICON icon) { 302 // We start with validating parameters. 303 if (!icon) 304 return NULL; 305 306 ScopedICONINFO icon_info; 307 BITMAP bitmap_info = { 0 }; 308 309 if (!::GetIconInfo(icon, &icon_info)) 310 return NULL; 311 312 if (!::GetObject(icon_info.hbmMask, sizeof(bitmap_info), &bitmap_info)) 313 return NULL; 314 315 gfx::Size icon_size(bitmap_info.bmWidth, bitmap_info.bmHeight); 316 return new SkBitmap(CreateSkBitmapFromHICONHelper(icon, icon_size)); 317} 318 319HICON IconUtil::CreateCursorFromDIB(const gfx::Size& icon_size, 320 const gfx::Point& hotspot, 321 const void* dib_bits, 322 size_t dib_size) { 323 BITMAPINFO icon_bitmap_info = {0}; 324 gfx::CreateBitmapHeader( 325 icon_size.width(), 326 icon_size.height(), 327 reinterpret_cast<BITMAPINFOHEADER*>(&icon_bitmap_info)); 328 329 base::win::ScopedGetDC dc(NULL); 330 base::win::ScopedCreateDC working_dc(CreateCompatibleDC(dc)); 331 base::win::ScopedGDIObject<HBITMAP> bitmap_handle( 332 CreateDIBSection(dc, 333 &icon_bitmap_info, 334 DIB_RGB_COLORS, 335 0, 336 0, 337 0)); 338 if (dib_size > 0) { 339 SetDIBits(0, 340 bitmap_handle, 341 0, 342 icon_size.height(), 343 dib_bits, 344 &icon_bitmap_info, 345 DIB_RGB_COLORS); 346 } 347 348 HBITMAP old_bitmap = reinterpret_cast<HBITMAP>( 349 SelectObject(working_dc, bitmap_handle)); 350 SetBkMode(working_dc, TRANSPARENT); 351 SelectObject(working_dc, old_bitmap); 352 353 base::win::ScopedGDIObject<HBITMAP> mask( 354 CreateBitmap(icon_size.width(), 355 icon_size.height(), 356 1, 357 1, 358 NULL)); 359 ICONINFO ii = {0}; 360 ii.fIcon = FALSE; 361 ii.xHotspot = hotspot.x(); 362 ii.yHotspot = hotspot.y(); 363 ii.hbmMask = mask; 364 ii.hbmColor = bitmap_handle; 365 366 return CreateIconIndirect(&ii); 367} 368 369SkBitmap IconUtil::CreateSkBitmapFromHICONHelper(HICON icon, 370 const gfx::Size& s) { 371 DCHECK(icon); 372 DCHECK(!s.IsEmpty()); 373 374 // Allocating memory for the SkBitmap object. We are going to create an ARGB 375 // bitmap so we should set the configuration appropriately. 376 SkBitmap bitmap; 377 bitmap.setConfig(SkBitmap::kARGB_8888_Config, s.width(), s.height()); 378 bitmap.allocPixels(); 379 bitmap.eraseARGB(0, 0, 0, 0); 380 SkAutoLockPixels bitmap_lock(bitmap); 381 382 // Now we should create a DIB so that we can use ::DrawIconEx in order to 383 // obtain the icon's image. 384 BITMAPV5HEADER h; 385 InitializeBitmapHeader(&h, s.width(), s.height()); 386 HDC hdc = ::GetDC(NULL); 387 uint32* bits; 388 HBITMAP dib = ::CreateDIBSection(hdc, reinterpret_cast<BITMAPINFO*>(&h), 389 DIB_RGB_COLORS, reinterpret_cast<void**>(&bits), NULL, 0); 390 DCHECK(dib); 391 HDC dib_dc = CreateCompatibleDC(hdc); 392 ::ReleaseDC(NULL, hdc); 393 DCHECK(dib_dc); 394 HGDIOBJ old_obj = ::SelectObject(dib_dc, dib); 395 396 // Windows icons are defined using two different masks. The XOR mask, which 397 // represents the icon image and an AND mask which is a monochrome bitmap 398 // which indicates the transparency of each pixel. 399 // 400 // To make things more complex, the icon image itself can be an ARGB bitmap 401 // and therefore contain an alpha channel which specifies the transparency 402 // for each pixel. Unfortunately, there is no easy way to determine whether 403 // or not a bitmap has an alpha channel and therefore constructing the bitmap 404 // for the icon is nothing but straightforward. 405 // 406 // The idea is to read the AND mask but use it only if we know for sure that 407 // the icon image does not have an alpha channel. The only way to tell if the 408 // bitmap has an alpha channel is by looking through the pixels and checking 409 // whether there are non-zero alpha bytes. 410 // 411 // We start by drawing the AND mask into our DIB. 412 size_t num_pixels = s.GetArea(); 413 memset(bits, 0, num_pixels * 4); 414 ::DrawIconEx(dib_dc, 0, 0, icon, s.width(), s.height(), 0, NULL, DI_MASK); 415 416 // Capture boolean opacity. We may not use it if we find out the bitmap has 417 // an alpha channel. 418 scoped_ptr<bool[]> opaque(new bool[num_pixels]); 419 for (size_t i = 0; i < num_pixels; ++i) 420 opaque[i] = !bits[i]; 421 422 // Then draw the image itself which is really the XOR mask. 423 memset(bits, 0, num_pixels * 4); 424 ::DrawIconEx(dib_dc, 0, 0, icon, s.width(), s.height(), 0, NULL, DI_NORMAL); 425 memcpy(bitmap.getPixels(), static_cast<void*>(bits), num_pixels * 4); 426 427 // Finding out whether the bitmap has an alpha channel. 428 bool bitmap_has_alpha_channel = PixelsHaveAlpha( 429 static_cast<const uint32*>(bitmap.getPixels()), num_pixels); 430 431 // If the bitmap does not have an alpha channel, we need to build it using 432 // the previously captured AND mask. Otherwise, we are done. 433 if (!bitmap_has_alpha_channel) { 434 uint32* p = static_cast<uint32*>(bitmap.getPixels()); 435 for (size_t i = 0; i < num_pixels; ++p, ++i) { 436 DCHECK_EQ((*p & 0xff000000), 0u); 437 if (opaque[i]) 438 *p |= 0xff000000; 439 else 440 *p &= 0x00ffffff; 441 } 442 } 443 444 ::SelectObject(dib_dc, old_obj); 445 ::DeleteObject(dib); 446 ::DeleteDC(dib_dc); 447 448 return bitmap; 449} 450 451// static 452bool IconUtil::CreateIconFileFromImageFamily( 453 const gfx::ImageFamily& image_family, 454 const base::FilePath& icon_path) { 455 // Creating a set of bitmaps corresponding to the icon images we'll end up 456 // storing in the icon file. Each bitmap is created by resizing the most 457 // appropriate image from |image_family| to the desired size. 458 gfx::ImageFamily resized_image_family; 459 if (!BuildResizedImageFamily(image_family, &resized_image_family)) 460 return false; 461 462 std::vector<SkBitmap> bitmaps; 463 scoped_refptr<base::RefCountedMemory> png_bytes; 464 if (!ConvertImageFamilyToBitmaps(resized_image_family, &bitmaps, &png_bytes)) 465 return false; 466 467 // Guaranteed true because BuildResizedImageFamily will provide at least one 468 // image < 256x256. 469 DCHECK(!bitmaps.empty()); 470 size_t bitmap_count = bitmaps.size(); // Not including PNG image. 471 // Including PNG image, if any. 472 size_t image_count = bitmap_count + (png_bytes.get() ? 1 : 0); 473 474 // Computing the total size of the buffer we need in order to store the 475 // images in the desired icon format. 476 size_t buffer_size = ComputeIconFileBufferSize(bitmaps); 477 // Account for the bytes needed for the PNG entry. 478 if (png_bytes.get()) 479 buffer_size += sizeof(ICONDIRENTRY) + png_bytes->size(); 480 481 // Setting the information in the structures residing within the buffer. 482 // First, we set the information which doesn't require iterating through the 483 // bitmap set and then we set the bitmap specific structures. In the latter 484 // step we also copy the actual bits. 485 std::vector<uint8> buffer(buffer_size); 486 ICONDIR* icon_dir = reinterpret_cast<ICONDIR*>(&buffer[0]); 487 icon_dir->idType = kResourceTypeIcon; 488 icon_dir->idCount = static_cast<WORD>(image_count); 489 // - 1 because there is already one ICONDIRENTRY in ICONDIR. 490 size_t icon_dir_count = image_count - 1; 491 492 size_t offset = sizeof(ICONDIR) + (sizeof(ICONDIRENTRY) * icon_dir_count); 493 for (size_t i = 0; i < bitmap_count; i++) { 494 ICONIMAGE* image = reinterpret_cast<ICONIMAGE*>(&buffer[offset]); 495 DCHECK_LT(offset, buffer_size); 496 size_t icon_image_size = 0; 497 SetSingleIconImageInformation(bitmaps[i], i, icon_dir, image, offset, 498 &icon_image_size); 499 DCHECK_GT(icon_image_size, 0U); 500 offset += icon_image_size; 501 } 502 503 // Add the PNG entry, if necessary. 504 if (png_bytes.get()) { 505 ICONDIRENTRY* entry = &icon_dir->idEntries[bitmap_count]; 506 entry->bWidth = 0; 507 entry->bHeight = 0; 508 entry->wPlanes = 1; 509 entry->wBitCount = 32; 510 entry->dwBytesInRes = static_cast<DWORD>(png_bytes->size()); 511 entry->dwImageOffset = static_cast<DWORD>(offset); 512 memcpy(&buffer[offset], png_bytes->front(), png_bytes->size()); 513 offset += png_bytes->size(); 514 } 515 516 DCHECK_EQ(offset, buffer_size); 517 518 std::string data(buffer.begin(), buffer.end()); 519 return base::ImportantFileWriter::WriteFileAtomically(icon_path, data); 520} 521 522bool IconUtil::PixelsHaveAlpha(const uint32* pixels, size_t num_pixels) { 523 for (const uint32* end = pixels + num_pixels; pixels != end; ++pixels) { 524 if ((*pixels & 0xff000000) != 0) 525 return true; 526 } 527 528 return false; 529} 530 531void IconUtil::InitializeBitmapHeader(BITMAPV5HEADER* header, int width, 532 int height) { 533 DCHECK(header); 534 memset(header, 0, sizeof(BITMAPV5HEADER)); 535 header->bV5Size = sizeof(BITMAPV5HEADER); 536 537 // Note that icons are created using top-down DIBs so we must negate the 538 // value used for the icon's height. 539 header->bV5Width = width; 540 header->bV5Height = -height; 541 header->bV5Planes = 1; 542 header->bV5Compression = BI_RGB; 543 544 // Initializing the bitmap format to 32 bit ARGB. 545 header->bV5BitCount = 32; 546 header->bV5RedMask = 0x00FF0000; 547 header->bV5GreenMask = 0x0000FF00; 548 header->bV5BlueMask = 0x000000FF; 549 header->bV5AlphaMask = 0xFF000000; 550 551 // Use the system color space. The default value is LCS_CALIBRATED_RGB, which 552 // causes us to crash if we don't specify the approprite gammas, etc. See 553 // <http://msdn.microsoft.com/en-us/library/ms536531(VS.85).aspx> and 554 // <http://b/1283121>. 555 header->bV5CSType = LCS_WINDOWS_COLOR_SPACE; 556 557 // Use a valid value for bV5Intent as 0 is not a valid one. 558 // <http://msdn.microsoft.com/en-us/library/dd183381(VS.85).aspx> 559 header->bV5Intent = LCS_GM_IMAGES; 560} 561 562void IconUtil::SetSingleIconImageInformation(const SkBitmap& bitmap, 563 size_t index, 564 ICONDIR* icon_dir, 565 ICONIMAGE* icon_image, 566 size_t image_offset, 567 size_t* image_byte_count) { 568 DCHECK(icon_dir != NULL); 569 DCHECK(icon_image != NULL); 570 DCHECK_GT(image_offset, 0U); 571 DCHECK(image_byte_count != NULL); 572 DCHECK_LT(bitmap.width(), kLargeIconSize); 573 DCHECK_LT(bitmap.height(), kLargeIconSize); 574 575 // We start by computing certain image values we'll use later on. 576 size_t xor_mask_size, bytes_in_resource; 577 ComputeBitmapSizeComponents(bitmap, 578 &xor_mask_size, 579 &bytes_in_resource); 580 581 icon_dir->idEntries[index].bWidth = static_cast<BYTE>(bitmap.width()); 582 icon_dir->idEntries[index].bHeight = static_cast<BYTE>(bitmap.height()); 583 icon_dir->idEntries[index].wPlanes = 1; 584 icon_dir->idEntries[index].wBitCount = 32; 585 icon_dir->idEntries[index].dwBytesInRes = bytes_in_resource; 586 icon_dir->idEntries[index].dwImageOffset = image_offset; 587 icon_image->icHeader.biSize = sizeof(BITMAPINFOHEADER); 588 589 // The width field in the BITMAPINFOHEADER structure accounts for the height 590 // of both the AND mask and the XOR mask so we need to multiply the bitmap's 591 // height by 2. The same does NOT apply to the width field. 592 icon_image->icHeader.biHeight = bitmap.height() * 2; 593 icon_image->icHeader.biWidth = bitmap.width(); 594 icon_image->icHeader.biPlanes = 1; 595 icon_image->icHeader.biBitCount = 32; 596 597 // We use a helper function for copying to actual bits from the SkBitmap 598 // object into the appropriate space in the buffer. We use a helper function 599 // (rather than just copying the bits) because there is no way to specify the 600 // orientation (bottom-up vs. top-down) of a bitmap residing in a .ico file. 601 // Thus, if we just copy the bits, we'll end up with a bottom up bitmap in 602 // the .ico file which will result in the icon being displayed upside down. 603 // The helper function copies the image into the buffer one scanline at a 604 // time. 605 // 606 // Note that we don't need to initialize the AND mask since the memory 607 // allocated for the icon data buffer was initialized to zero. The icon we 608 // create will therefore use an AND mask containing only zeros, which is OK 609 // because the underlying image has an alpha channel. An AND mask containing 610 // only zeros essentially means we'll initially treat all the pixels as 611 // opaque. 612 unsigned char* image_addr = reinterpret_cast<unsigned char*>(icon_image); 613 unsigned char* xor_mask_addr = image_addr + sizeof(BITMAPINFOHEADER); 614 CopySkBitmapBitsIntoIconBuffer(bitmap, xor_mask_addr, xor_mask_size); 615 *image_byte_count = bytes_in_resource; 616} 617 618void IconUtil::CopySkBitmapBitsIntoIconBuffer(const SkBitmap& bitmap, 619 unsigned char* buffer, 620 size_t buffer_size) { 621 SkAutoLockPixels bitmap_lock(bitmap); 622 unsigned char* bitmap_ptr = static_cast<unsigned char*>(bitmap.getPixels()); 623 size_t bitmap_size = bitmap.height() * bitmap.width() * 4; 624 DCHECK_EQ(buffer_size, bitmap_size); 625 for (size_t i = 0; i < bitmap_size; i += bitmap.width() * 4) { 626 memcpy(buffer + bitmap_size - bitmap.width() * 4 - i, 627 bitmap_ptr + i, 628 bitmap.width() * 4); 629 } 630} 631 632size_t IconUtil::ComputeIconFileBufferSize(const std::vector<SkBitmap>& set) { 633 DCHECK(!set.empty()); 634 635 // We start by counting the bytes for the structures that don't depend on the 636 // number of icon images. Note that sizeof(ICONDIR) already accounts for a 637 // single ICONDIRENTRY structure, which is why we subtract one from the 638 // number of bitmaps. 639 size_t total_buffer_size = sizeof(ICONDIR); 640 size_t bitmap_count = set.size(); 641 total_buffer_size += sizeof(ICONDIRENTRY) * (bitmap_count - 1); 642 // May not have all icon sizes, but must have at least up to medium icon size. 643 DCHECK_GE(bitmap_count, kNumIconDimensionsUpToMediumSize); 644 645 // Add the bitmap specific structure sizes. 646 for (size_t i = 0; i < bitmap_count; i++) { 647 size_t xor_mask_size, bytes_in_resource; 648 ComputeBitmapSizeComponents(set[i], 649 &xor_mask_size, 650 &bytes_in_resource); 651 total_buffer_size += bytes_in_resource; 652 } 653 return total_buffer_size; 654} 655 656void IconUtil::ComputeBitmapSizeComponents(const SkBitmap& bitmap, 657 size_t* xor_mask_size, 658 size_t* bytes_in_resource) { 659 // The XOR mask size is easy to calculate since we only deal with 32bpp 660 // images. 661 *xor_mask_size = bitmap.width() * bitmap.height() * 4; 662 663 // Computing the AND mask is a little trickier since it is a monochrome 664 // bitmap (regardless of the number of bits per pixels used in the XOR mask). 665 // There are two things we must make sure we do when computing the AND mask 666 // size: 667 // 668 // 1. Make sure the right number of bytes is allocated for each AND mask 669 // scan line in case the number of pixels in the image is not divisible by 670 // 8. For example, in a 15X15 image, 15 / 8 is one byte short of 671 // containing the number of bits we need in order to describe a single 672 // image scan line so we need to add a byte. Thus, we need 2 bytes instead 673 // of 1 for each scan line. 674 // 675 // 2. Make sure each scan line in the AND mask is 4 byte aligned (so that the 676 // total icon image has a 4 byte alignment). In the 15X15 image example 677 // above, we can not use 2 bytes so we increase it to the next multiple of 678 // 4 which is 4. 679 // 680 // Once we compute the size for a singe AND mask scan line, we multiply that 681 // number by the image height in order to get the total number of bytes for 682 // the AND mask. Thus, for a 15X15 image, we need 15 * 4 which is 60 bytes 683 // for the monochrome bitmap representing the AND mask. 684 size_t and_line_length = (bitmap.width() + 7) >> 3; 685 and_line_length = (and_line_length + 3) & ~3; 686 size_t and_mask_size = and_line_length * bitmap.height(); 687 size_t masks_size = *xor_mask_size + and_mask_size; 688 *bytes_in_resource = masks_size + sizeof(BITMAPINFOHEADER); 689} 690