@@ -275,7 +275,7 @@ bool UIImage::loadPngFromStream(unsigned char *data, int nLength)
275
275
m_imageInfo.width = info_ptr->width ;
276
276
m_imageInfo.isPremultipliedAlpha = false ;
277
277
m_imageInfo.bitsPerComponent = info_ptr->bit_depth ;
278
- m_imageInfo.hasAlpha = true ;
278
+ m_imageInfo.hasAlpha = info_ptr-> color_type & PNG_COLOR_MASK_ALPHA ;
279
279
280
280
// convert to appropriate format, we now only support RGBA8888
281
281
if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
@@ -296,30 +296,38 @@ bool UIImage::loadPngFromStream(unsigned char *data, int nLength)
296
296
png_set_strip_16 (png_ptr);
297
297
}
298
298
299
- // expand paletted or RGB images with transparency to full alpha channels so the data will be
300
- // available as RGBA quatets
299
+ // adds a full alpha channel if there is transparency information
300
+ // in a tRNS chunk
301
301
if (png_get_valid (png_ptr, info_ptr, PNG_INFO_tRNS))
302
302
{
303
303
png_set_tRNS_to_alpha (png_ptr);
304
+ m_imageInfo.hasAlpha = true ;
304
305
}
305
306
306
307
// add the alpha channel if it has not
307
308
if (info_ptr->color_type == PNG_COLOR_TYPE_RGB || info_ptr->color_type == PNG_COLOR_TYPE_GRAY)
308
309
{
309
310
png_set_add_alpha (png_ptr, 255 , PNG_FILLER_AFTER);
311
+ m_imageInfo.hasAlpha = true ;
310
312
}
311
313
312
314
// allocate memory and read data
313
- m_imageInfo.data = new unsigned char [m_imageInfo.height * m_imageInfo.width * 4 ];
315
+ int bytesPerComponent = 3 ;
316
+ if (m_imageInfo.hasAlpha )
317
+ {
318
+ bytesPerComponent = 4 ;
319
+ }
320
+
321
+ m_imageInfo.data = new unsigned char [m_imageInfo.height * m_imageInfo.width * bytesPerComponent];
314
322
rowPointers = (png_bytep*)png_mem_alloc (sizeof (png_bytep) * m_imageInfo.height );
315
323
for (unsigned int i = 0 ; i < m_imageInfo.height ; ++i)
316
324
{
317
- rowPointers[i] = (png_bytep)png_mem_alloc (m_imageInfo.width * 4 );
325
+ rowPointers[i] = (png_bytep)png_mem_alloc (m_imageInfo.width * bytesPerComponent );
318
326
}
319
327
png_read_image (png_ptr, rowPointers);
320
328
321
329
// copy data to image info
322
- int bytesPerRow = m_imageInfo.width * 4 ;
330
+ int bytesPerRow = m_imageInfo.width * bytesPerComponent ;
323
331
for (unsigned int j = 0 ; j < m_imageInfo.height ; ++j)
324
332
{
325
333
memcpy (m_imageInfo.data + j * bytesPerRow, rowPointers[j], bytesPerRow);
0 commit comments