ximapng.cpp

来自「君正早期ucos系统(只有早期的才不没有打包成库),MPLAYER,文件系统,图」· C++ 代码 · 共 646 行 · 第 1/2 页

CPP
646
字号
/*
 * File:	ximapng.cpp
 * Purpose:	Platform Independent PNG Image Class Loader and Writer
 * 07/Aug/2001 Davide Pizzolato - www.xdp.it
 * CxImage version 5.99c 17/Oct/2004
 */

#include "ximapng.h"

#if CXIMAGE_SUPPORT_PNG

#include "ximaiter.h"
extern "C"{
	void *ex_png_malloc(unsigned int size)
	{
		return CImageMemMgr::malloc(size);
	}
	
  void ex_png_free(void * mem)
  {
  	CImageMemMgr::free(mem);
  }
}
////////////////////////////////////////////////////////////////////////////////
void CxImagePNG::ima_png_error(png_struct *png_ptr, char *message)
{
	strcpy(info.szLastError,message);
	longjmp(png_ptr->jmpbuf, 1);
}
////////////////////////////////////////////////////////////////////////////////
void CxImagePNG::expand2to4bpp(BYTE* prow)
{
	BYTE *psrc,*pdst;
	BYTE pos,idx;
	for(long x=head.biWidth-1;x>=0;x--){
		psrc = prow + ((2*x)>>3);
		pdst = prow + ((4*x)>>3);
		pos = (BYTE)(2*(3-x%4));
		idx = (BYTE)((*psrc & (0x03<<pos))>>pos);
		pos = (BYTE)(4*(1-x%2));
		*pdst &= ~(0x0F<<pos);
		*pdst |= (idx & 0x0F)<<pos;
	}
}
////////////////////////////////////////////////////////////////////////////////
void CxImagePNG::expand2to4bpp(BYTE* prow,int width)
{
	BYTE *psrc,*pdst;
	BYTE pos,idx;
	for(long x=width-1;x>=0;x--){
		psrc = prow + ((2*x)>>3);
		pdst = prow + ((4*x)>>3);
		pos = (BYTE)(2*(3-x%4));
		idx = (BYTE)((*psrc & (0x03<<pos))>>pos);
		pos = (BYTE)(4*(1-x%2));
		*pdst &= ~(0x0F<<pos);
		*pdst |= (idx & 0x0F)<<pos;
	}
}
////////////////////////////////////////////////////////////////////////////////
bool CxImagePNG::Decode(CxFile *hFile)
{
	int number_passes;
	png_struct *png_ptr;
	png_info *info_ptr;
	BYTE *row_pointers=NULL;
	RGBQUAD* pal; 
	DWORD ip;

	unsigned int scale = 0,bw;
	unsigned int msize;
	unsigned int fsize;
	int yscale = 0;
	unsigned int *pd;
  int y=0;

	CImageIterator iter(this);
	int row_stride;
  int pixel_depth;
  png_color_16 my_background={ 0, 192, 192, 192, 0 };
	png_color_16 *image_background;
  //try {
	/* Create and initialize the png_struct with the desired error handler
    * functions.  If you want to use the default stderr and longjump method,
    * you can supply NULL for the last three parameters.  We also supply the
    * the compiler header file version, so that we know if the application
    * was compiled with a compatible version of the library.  REQUIRED
    */
    
	png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING,(void *)NULL,NULL,NULL);
	if (png_ptr == NULL){
		printf("Failed to create PNG structure\n");
		goto EXIT;
	}
   
	/* Allocate/initialize the memory for image information.  REQUIRED. */
	info_ptr = png_create_info_struct(png_ptr);
	if (info_ptr == NULL) {
		png_destroy_read_struct(&png_ptr, (png_infopp)NULL, (png_infopp)NULL);
		printf("Failed to initialize PNG info structure\n");
		goto EXIT;
	}

    /* Set error handling if you are using the setjmp/longjmp method (this is
    * the normal method of doing things with libpng).  REQUIRED unless you
    * set up your own error handlers in the png_create_read_struct() earlier.
    */
  if (setjmp(png_ptr->jmpbuf)) {
		/* Free all of the memory associated with the png_ptr and info_ptr */
		if (row_pointers) delete[] row_pointers;
		png_destroy_read_struct(&png_ptr, &info_ptr, (png_infopp)NULL);
		printf("%s setjmp error!\n",__FILE__);
		goto EXIT;
		
	}
	/* set up the input control */
	//png_init_io(png_ptr, hFile);

	// use custom I/O functions
  png_set_read_fn(png_ptr, hFile, (png_rw_ptr)user_read_data);
	png_set_error_fn(png_ptr,info.szLastError,(png_error_ptr)user_error_fn,NULL);
  /* read the file information */
	png_read_info(png_ptr, info_ptr);
  //png_set_sCAL_s(png_ptr, info_ptr,2,480 /2 ,272 / 2);
	/* allocate the memory to hold the image using the fields of png_info. */
	
	if (info_ptr->pixel_depth != 32){
		//<yeonjun jeong> preserve original background info.
		#if 0
		if (png_get_bKGD(png_ptr, info_ptr, &image_background))
			png_set_background(png_ptr, image_background,PNG_BACKGROUND_GAMMA_FILE, 1, 1.0);
		else
			png_set_background(png_ptr, &my_background,PNG_BACKGROUND_GAMMA_SCREEN, 0, 1.0);
		#endif
// <vho> - we call png_set_bgr() below
// <vho>	//<yeonjun jeong> safe check
// <vho>	if (info_ptr->pixel_depth > 16 ) info_ptr->color_type = COLORTYPE_COLOR;
	}

	//<DP> hack for images with alpha channel
	if (info_ptr->pixel_depth == 32){
//		info.nBkgndIndex = 0; //enable transparency
		if (png_get_bKGD(png_ptr, info_ptr, &image_background)){
			info.nBkgndColor.rgbRed   = (BYTE)image_background->red;
			info.nBkgndColor.rgbGreen = (BYTE)image_background->green;
			info.nBkgndColor.rgbBlue  = (BYTE)image_background->blue;
			info.nBkgndColor.rgbReserved = 0;	// <vho>
		}
	}

	/* tell libpng to strip 16 bit depth files down to 8 bits */
	if (info_ptr->bit_depth == 16)	png_set_strip_16(png_ptr);

	pixel_depth=info_ptr->pixel_depth;
	if (pixel_depth >  16 ) pixel_depth=24;
	if (pixel_depth == 16 ) pixel_depth=8;
	
	msize = info_ptr->width * info_ptr->height;
	
	fsize = GetFreeMem() / 3;
	bw = 1;
	while(fsize < msize)
	{
		msize /= 4;
		bw *= 2;
	}
	if(bw > 8)
		bw = 8;
	//info_ptr.scale_denom = bw;
	scale = bw;
	Create(info_ptr->width / scale, info_ptr->height / scale, pixel_depth, CXIMAGE_FORMAT_PNG);
  //printf("width = %d,height = %d\n",info_ptr->width,info_ptr->height);
	/* get metrics */
	switch (info_ptr->phys_unit_type)
	{
	case PNG_RESOLUTION_UNKNOWN:
		SetXDPI(info_ptr->x_pixels_per_unit);
		SetYDPI(info_ptr->y_pixels_per_unit);
		break;
	case PNG_RESOLUTION_METER:
		SetXDPI((long)floor(info_ptr->x_pixels_per_unit * 254.0 / 10000.0 + 0.5));
		SetYDPI((long)floor(info_ptr->y_pixels_per_unit * 254.0 / 10000.0 + 0.5));
		break;
	}

	if (info_ptr->num_palette>0)
	  SetPalette((rgb_color*)info_ptr->palette,info_ptr->num_palette);
	else if (info_ptr->bit_depth ==2) { //<DP> needed for 2 bpp grayscale PNGs
		SetPaletteColor(0,0,0,0);
		SetPaletteColor(1,85,85,85);
		SetPaletteColor(2,170,170,170);
		SetPaletteColor(3,255,255,255);
	} else SetGrayPalette(); //<DP> needed for grayscale PNGs

	// simple transparency (the real PGN transparency is more complex)
	if (info_ptr->num_trans!=0){
		//palette transparency
		pal=GetPalette();
		if (pal){
			
			for (ip=0;ip<min(head.biClrUsed,(unsigned long)info_ptr->num_trans);ip++)
				pal[ip].rgbReserved=info_ptr->trans[ip];
			if (info_ptr->num_trans==1 && pal[0].rgbReserved==0){
				info.nBkgndIndex = 0;
			} else {
				info.bAlphaPaletteEnabled=true;
				for (;ip<head.biClrUsed;ip++)
					pal[ip].rgbReserved=255;
			}
		}
	}
	//printf("color_type = %d PNG_COLOR_TYPE_RGB_ALPHA = %d\n",info_ptr->color_type,PNG_COLOR_TYPE_RGB_ALPHA);
	//printf("pixel_depth = %d PNG_COLOR_TYPE_GRAY_ALPHA = %d\n",info_ptr->pixel_depth,PNG_COLOR_TYPE_GRAY_ALPHA);
	
	if (info_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA || //Alpha channel
		(info_ptr->color_type == PNG_COLOR_TYPE_GRAY_ALPHA && info_ptr->pixel_depth == 32)){
		if (info_ptr->color_type == PNG_COLOR_TYPE_GRAY_ALPHA){
			png_set_gray_to_rgb(png_ptr);
			png_set_expand(png_ptr);
		}
#if CXIMAGE_SUPPORT_ALPHA	// <vho>

		png_set_filler(png_ptr, 0xff, PNG_FILLER_AFTER);
		
		AlphaCreate();
#else
		png_set_strip_alpha(png_ptr);
#endif	//CXIMAGE_SUPPORT_ALPHA
	}

	// <vho> - flip the RGB pixels to BGR (or RGBA to BGRA)
	if (info_ptr->color_type & PNG_COLOR_MASK_COLOR) png_set_bgr(png_ptr);

	// <vho> - handle cancel
	if (info.nEscape) longjmp(png_ptr->jmpbuf, 1);

	//allocate the buffer
	row_stride = info_ptr->width * ((info_ptr->pixel_depth+7)>>3);
	row_pointers = new BYTE[10+row_stride];
	pd   = new unsigned int[info_ptr->width * 4];
	// turn on interlace handling
	number_passes = png_set_interlace_handling(png_ptr);

	if (number_passes>1){
		SetCodecOption(1);
	} else {
		SetCodecOption(0);
	}

	for (int pass=0; pass< number_passes; pass++) {
		iter.Upset();
		y = 0;
		do	{
			
			// <vho> - handle cancel
			if (info.nEscape) longjmp(png_ptr->jmpbuf, 1);

#if CXIMAGE_SUPPORT_ALPHA	// <vho>
			//printf("AlphaIsValid = %d\n",AlphaIsValid());
			if (!AlphaIsValid())
#endif // CXIMAGE_SUPPORT_ALPHA
			{
				//recover data from previous scan
				if (info_ptr->interlace_type && pass>0)
					iter.GetRow(row_pointers, info.dwEffWidth);
				
				//copy the pixels
				long ax,ay;
				ay = head.biHeight-1-y;
				for(yscale = 0;yscale < scale;yscale++)
				{
				//read next row
					png_read_row(png_ptr, row_pointers, NULL);
	// <vho> - already done by png_set_bgr()
	// <vho>			//HACK BY OP && (<DP> for interlace, swap only in the last pass)
	// <vho>			if (info_ptr->color_type==COLORTYPE_COLOR && pass==(number_passes-1))
	// <vho>				RGBtoBGR(row_pointers, info.dwEffWidth);
					//<DP> expand 2 bpp images only in the last pass
					if (info_ptr->bit_depth==2 && pass==(number_passes-1))
						expand2to4bpp(row_pointers,info_ptr->width);
          //printf("%d %d %d\n",info_ptr->width,head.biWidth,scale);
					switch(info_ptr->bit_depth)
					{		
						case 24:	
					 	 for(ax=0;ax<head.biWidth;ax++){
							for(int i = 0;i<scale;i++)
							{
								if((i == 0)&&(yscale == 0))
								{
									pd[ax*3 + 0] = (unsigned int)row_pointers[ax*3*scale + 0];
									pd[ax*3 + 1] = (unsigned int)row_pointers[ax*3*scale + 1];
									pd[ax*3 + 2] = (unsigned int)row_pointers[ax*3*scale + 2];
								}else
								{
									pd[ax*3 + 0] += (unsigned int)row_pointers[(ax*scale + i) * 3 + 0];
									pd[ax*3 + 1] += (unsigned int)row_pointers[(ax*scale + i) * 3 + 1];
									pd[ax*3 + 2] += (unsigned int)row_pointers[(ax*scale + i) * 3 + 2];
								}	
						  }	  
						}
						break;
					}
				}
				iter.SetRow(row_pointers, info.dwEffWidth);
					
				//go on
				iter.PrevRow();
			}
#if CXIMAGE_SUPPORT_ALPHA	// <vho>
			else { //alpha blend

				//compute the correct position of the line
				long ax,ay;
				ay = head.biHeight-1-y;
				BYTE* prow= iter.GetRow(ay);

#if 0
				//recover data from previous scan
				if (info_ptr->interlace_type && pass>0 && pass!=7){
					for(ax=head.biWidth;ax>=0;ax--){
						row_pointers[ax*4]=prow[3*ax];
						row_pointers[ax*4+1]=prow[3*ax+1];
						row_pointers[ax*4+2]=prow[3*ax+2];

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?