当前位置: 首页>>代码示例>>C++>>正文


C++ png_set_read_fn函数代码示例

本文整理汇总了C++中png_set_read_fn函数的典型用法代码示例。如果您正苦于以下问题:C++ png_set_read_fn函数的具体用法?C++ png_set_read_fn怎么用?C++ png_set_read_fn使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了png_set_read_fn函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: SplashDecodePng

int
SplashDecodePng(Splash * splash, png_rw_ptr read_func, void *io_ptr)
{
    int stride;
    ImageFormat srcFormat;
    png_uint_32 i, rowbytes;
    png_bytepp row_pointers = NULL;
    png_bytep image_data = NULL;
    int success = 0;
    double gamma;

    png_structp png_ptr = NULL;
    png_infop info_ptr = NULL;

    png_uint_32 width, height;
    int bit_depth, color_type;

    ImageRect srcRect, dstRect;

    png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
    if (!png_ptr) {
        goto done;
    }

    info_ptr = png_create_info_struct(png_ptr);
    if (!info_ptr) {
        goto done;
    }

#ifdef __APPLE__
    /* use setjmp/longjmp versions that do not save/restore the signal mask */
    if (_setjmp(png_set_longjmp_fn(png_ptr, _longjmp, sizeof(jmp_buf)))) {
#else
    if (setjmp(png_jmpbuf(png_ptr))) {
#endif
        goto done;
    }

    png_set_read_fn(png_ptr, io_ptr, read_func);

    png_set_sig_bytes(png_ptr, SIG_BYTES);      /* we already read the 8 signature bytes */

    png_read_info(png_ptr, info_ptr);   /* read all PNG info up to image data */

    png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type,
        NULL, NULL, NULL);

    /* expand palette images to RGB, low-bit-depth grayscale images to 8 bits,
     * transparency chunks to full alpha channel; strip 16-bit-per-sample
     * images to 8 bits per sample; and convert grayscale to RGB[A]
     * this may be sub-optimal but this simplifies implementation */

    png_set_expand(png_ptr);
    png_set_tRNS_to_alpha(png_ptr);
    png_set_filler(png_ptr, 0xff, PNG_FILLER_AFTER);
    png_set_strip_16(png_ptr);
    png_set_gray_to_rgb(png_ptr);

    if (png_get_gAMA(png_ptr, info_ptr, &gamma))
        png_set_gamma(png_ptr, 2.2, gamma);

    png_set_interlace_handling(png_ptr);
    png_read_update_info(png_ptr, info_ptr);

    rowbytes = png_get_rowbytes(png_ptr, info_ptr);

    if (!SAFE_TO_ALLOC(rowbytes, height)) {
        goto done;
    }

    if ((image_data = (unsigned char *) malloc(rowbytes * height)) == NULL) {
        goto done;
    }

    if (!SAFE_TO_ALLOC(height, sizeof(png_bytep))) {
        goto done;
    }
    if ((row_pointers = (png_bytepp) malloc(height * sizeof(png_bytep)))
            == NULL) {
        goto done;
    }

    for (i = 0; i < height; ++i)
        row_pointers[i] = image_data + i * rowbytes;

    png_read_image(png_ptr, row_pointers);

    SplashCleanup(splash);

    splash->width = width;
    splash->height = height;

    if (!SAFE_TO_ALLOC(splash->width, splash->imageFormat.depthBytes)) {
        goto done;
    }
    stride = splash->width * splash->imageFormat.depthBytes;

    if (!SAFE_TO_ALLOC(splash->height, stride)) {
        goto done;
    }
//.........这里部分代码省略.........
开发者ID:JetBrains,项目名称:jdk8u_jdk,代码行数:101,代码来源:splashscreen_png.c

示例2: Read

	int Read ( byte **data, int *width, int *height )
	{
		// Setup the pointers
		*data = NULL;
		*width = 0;
		*height = 0;

		// Make sure we're actually reading PNG data.
		const int SIGNATURE_LEN = 8;

		byte ident[SIGNATURE_LEN];
		memcpy (ident, buf, SIGNATURE_LEN);

		if ( !png_check_sig (ident, SIGNATURE_LEN) )
		{
			ri->Printf (PRINT_ERROR, "PNG signature not found in given image.");
			return 0;
		}

		png_ptr = png_create_read_struct (PNG_LIBPNG_VER_STRING, NULL, png_print_error, png_print_warning);
		if ( png_ptr == NULL )
		{
			ri->Printf (PRINT_ERROR, "Could not allocate enough memory to load the image.");
			return 0;
		}

		info_ptr = png_create_info_struct (png_ptr);
		if ( setjmp (png_jmpbuf (png_ptr)) )
		{
			return 0;
		}

		// We've read the signature
		offset += SIGNATURE_LEN;

		// Setup reading information, and read header
		png_set_read_fn (png_ptr, (png_voidp)this, &user_read_data);
#ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
		// This generic "ignore all, except required chunks" requires 1.6.0 or newer"
		png_set_keep_unknown_chunks (png_ptr, PNG_HANDLE_CHUNK_NEVER, NULL, -1);
#endif
		png_set_sig_bytes (png_ptr, SIGNATURE_LEN);
		png_read_info (png_ptr, info_ptr);

		png_uint_32 width_;
		png_uint_32 height_;
		int depth;
		int colortype;

		png_get_IHDR (png_ptr, info_ptr, &width_, &height_, &depth, &colortype, NULL, NULL, NULL);

		// While modern OpenGL can handle non-PoT textures, it's faster to handle only PoT
		// so that the graphics driver doesn't have to fiddle about with the texture when uploading.
		
		/*
		if ( !IsPowerOfTwo (width_) || !IsPowerOfTwo (height_) )
		{
			ri->Printf (PRINT_ERROR, "Width or height is not a power-of-two.\n");
			return 0;
		}
		*/

		// This function is equivalent to using what used to be LoadPNG32. LoadPNG8 also existed,
		// but this only seemed to be used by the RMG system which does not work in JKA. If this
		// does need to be re-implemented, then colortype should be PNG_COLOR_TYPE_PALETTE or
		// PNG_COLOR_TYPE_GRAY.
		if ( colortype != PNG_COLOR_TYPE_RGB && colortype != PNG_COLOR_TYPE_RGBA )
		{
			ri->Printf (PRINT_ERROR, "Image is not 24-bit or 32-bit.");
			return 0;
		}

		// Read the png data
		if ( colortype == PNG_COLOR_TYPE_RGB )
		{
			// Expand RGB -> RGBA
			png_set_add_alpha (png_ptr, 0xff, PNG_FILLER_AFTER);
		}

		png_read_update_info (png_ptr, info_ptr);

		// We always assume there are 4 channels. RGB channels are expanded to RGBA when read.
		byte *tempData = (byte *)ri->Z_Malloc (width_ * height_ * 4, TAG_TEMP_PNG, qfalse, 4);
		if ( !tempData )
		{
			ri->Printf (PRINT_ERROR, "Could not allocate enough memory to load the image.");
			return 0;
		}

		// Dynamic array of row pointers, with 'height' elements, initialized to NULL.
		byte **row_pointers = (byte **)ri->Hunk_AllocateTempMemory (sizeof (byte *) * height_);
		if ( !row_pointers )
		{
			ri->Printf (PRINT_ERROR, "Could not allocate enough memory to load the image.");

			ri->Z_Free (tempData);

			return 0;
		}

//.........这里部分代码省略.........
开发者ID:cagelight,项目名称:jaownt,代码行数:101,代码来源:tr_image_png.cpp

示例3: memset

void png_reader::init()
{
    FILE *fp=fopen(fileName_.c_str(),"rb");
    if (!fp) throw image_reader_exception("cannot open image file "+fileName_);
    png_byte header[8];
    memset(header,0,8);
    if ( fread(header,1,8,fp) != 8)
    {
        fclose(fp);
        throw image_reader_exception("Could not read " + fileName_);
    }
    int is_png=!png_sig_cmp(header,0,8);
    if (!is_png)
    {
        fclose(fp);
        throw image_reader_exception(fileName_ + " is not a png file");
    }
    png_structp png_ptr = png_create_read_struct
        (PNG_LIBPNG_VER_STRING,0,0,0);

    if (!png_ptr)
    {
        fclose(fp);
        throw image_reader_exception("failed to allocate png_ptr");
    }

    // catch errors in a custom way to avoid the need for setjmp
    png_set_error_fn(png_ptr, png_get_error_ptr(png_ptr), user_error_fn, user_warning_fn);

    png_infop info_ptr;
    try
    {
        info_ptr = png_create_info_struct(png_ptr);
        if (!info_ptr)
        {
            png_destroy_read_struct(&png_ptr,0,0);
            fclose(fp);
            throw image_reader_exception("failed to create info_ptr");
        }
    }
    catch (std::exception const& ex)
    {
        png_destroy_read_struct(&png_ptr,0,0);
        fclose(fp);
        throw;
    }

    png_set_read_fn(png_ptr, (png_voidp)fp, png_read_data);

    png_set_sig_bytes(png_ptr,8);
    png_read_info(png_ptr, info_ptr);

    png_uint_32  width, height;
    png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth_, &color_type_,0,0,0);

    width_=width;
    height_=height;

    MAPNIK_LOG_DEBUG(png_reader) << "png_reader: bit_depth=" << bit_depth_ << ",color_type=" << color_type_;

    png_destroy_read_struct(&png_ptr,&info_ptr,0);
    fclose(fp);
}
开发者ID:rory,项目名称:mapnik,代码行数:63,代码来源:png_reader.cpp

示例4: ReadPNG


//.........这里部分代码省略.........

    file = fopen( filename, "rb" );
    if ( !file || fread( signature, 1, 8, file ) != 8)
        longjmp ( err_jmp, (int)errFileOpen );

    /* check the signature */
    if ( png_sig_cmp( signature, 0, 8 ) != 0 )
        longjmp( err_jmp, (int)errUnsupportedFileFormat );

    /* create a pointer to the png read structure */
    png_ptr = png_create_read_struct( PNG_LIBPNG_VER_STRING, NULL, NULL, NULL );
    if ( !png_ptr )
        longjmp( err_jmp, (int)errMemoryAllocation );

    /* create a pointer to the png info structure */
    info_ptr = png_create_info_struct( png_ptr );
    if ( !info_ptr )
        longjmp( err_jmp, (int)errMemoryAllocation );

    /* create a pointer to the png end-info structure */
    end_info = png_create_info_struct(png_ptr);
    if (!end_info)
        longjmp( err_jmp, (int)errMemoryAllocation );

    /* bamboozle the PNG longjmp buffer */
    /*generic PNG error handler*/
    /* error will always == 1 which == errLib */
//    error = png_setjmp(png_ptr);
    error = setjmp( png_jmpbuf( png_ptr ) );
    if ( error > 0 )
        longjmp( err_jmp, error );

    /* set function pointers in the PNG library, for read callbacks */
    png_set_read_fn(png_ptr, (png_voidp) file, user_read_data);

    /*let the read functions know that we have already read the 1st 8 bytes */
    png_set_sig_bytes( png_ptr, 8 );

    /* read all PNG data up to the image data */
    png_read_info( png_ptr, info_ptr );

    /* extract the data we need to form the HBITMAP from the PNG header */
    png_get_IHDR( png_ptr, info_ptr, &Width, &Height, &BitDepth, &ColorType,
        &InterlaceType, NULL, NULL);

    img->width = (unsigned int) Width;
    img->height = (unsigned int) Height;

    img->bits_per_pixel = (unsigned char)32;
    img->scan_width = Width * 4;

    /* convert 16-bit images to 8-bit images */
    if (BitDepth == 16)
        png_set_strip_16(png_ptr);

    /* These are not really required per Rice format spec,
     * but is done just in case someone uses them.
     */
    /* convert palette color to rgb color */
    if (ColorType == PNG_COLOR_TYPE_PALETTE) {
        png_set_palette_to_rgb(png_ptr);
        ColorType = PNG_COLOR_TYPE_RGB;
    }

    /* expand 1,2,4 bit gray scale to 8 bit gray scale */
    if (ColorType == PNG_COLOR_TYPE_GRAY && BitDepth < 8)
开发者ID:AreaScout,项目名称:mupen64plus-odroid,代码行数:67,代码来源:pngrw.c

示例5: malloc

/**
 * @brief Opens an npng struct from an SDL_RWops. It does not close the RWops.
 *
 *    @param rw SDL_RWops to create npng from.
 *    @return npng created from rw.
 */
npng_t *npng_open( SDL_RWops *rw )
{
   png_byte header[8]; /* Maximum size to check. */
   npng_t *npng;

   /* Allocate memory. */
   npng = malloc( sizeof(npng_t) );
   if (npng == NULL) {
      WARN("Out of memory.");
      return NULL;
   }
   memset( npng, 0, sizeof(npng_t) );

   /* Set up struct. */
   npng->rw       = rw;
   npng->png_ptr  = png_create_read_struct( PNG_LIBPNG_VER_STRING, NULL, NULL, NULL );
   if (npng->png_ptr == NULL) {
      WARN("png_create_read_struct failed");
      goto ERR_FAIL;
   }
   npng->info_ptr = png_create_info_struct( npng->png_ptr );
   if (npng->info_ptr == NULL) {
      WARN("png_create_info_struct failed");
      goto ERR_FAIL;
   }

   /* Check header. */
   SDL_RWread( rw, header, 8, 1 );
   if (png_sig_cmp(header, 0, 8)) {
      WARN("RWops not recognized as a PNG file.");
      goto ERR_FAIL;
   }

   /* Set up for reading. */
   png_set_read_fn( npng->png_ptr, (png_voidp) rw, npng_read );

   /* Set up long jump for IO. */
   if (setjmp( png_jmpbuf( npng->png_ptr )) ) {
      WARN("Error during setjmp");
      goto ERR_FAIL;
   }

   /* We've already checked sig. */
   png_set_sig_bytes( npng->png_ptr, 8 );

   /* Get start. */
   npng->start = SDL_RWtell( npng->rw );

   /* Get info. */
   npng_info( npng );

   /* Load text. */
   png_get_text( npng->png_ptr, npng->info_ptr, &npng->text_ptr, &npng->num_text );

   return npng;

ERR_FAIL:
#if 0 /* Memory leaks are better than segfaults. */
   if (npng != NULL) {
      if (npng->png_ptr != NULL)
         png_destroy_read_struct( &npng->png_ptr, (npng->info_ptr != NULL) ? &npng->info_ptr : NULL, NULL );
      free(npng);
   }
#endif
   return NULL;
}
开发者ID:Crockadavin,项目名称:naev,代码行数:72,代码来源:npng.c

示例6: png_create_read_struct

// load in the image data
IImage* CImageLoaderPng::loadImage(irr::io::IReadFile* file)
{
#ifdef _IRR_COMPILE_WITH_LIBPNG_
    if (!file)
        return 0;

    Image = 0;
    RowPointers = 0;

    png_byte buffer[8];
    // Read the first few bytes of the PNG file
    if( file->read(buffer, 8) != 8 )
    {
        os::Printer::log("LOAD PNG: can't read file\n", file->getFileName(), ELL_ERROR);
        return 0;
    }

    // Check if it really is a PNG file
    if( png_sig_cmp(buffer, 0, 8) )
    {
        os::Printer::log("LOAD PNG: not really a png\n", file->getFileName(), ELL_ERROR);
        return 0;
    }

    // Allocate the png read struct
    png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING,
                          NULL, (png_error_ptr)png_cpexcept_error, NULL);
    if (!png_ptr)
    {
        os::Printer::log("LOAD PNG: Internal PNG create read struct failure\n", file->getFileName(), ELL_ERROR);
        return 0;
    }

    // Allocate the png info struct
    png_infop info_ptr = png_create_info_struct(png_ptr);
    if (!info_ptr)
    {
        os::Printer::log("LOAD PNG: Internal PNG create info struct failure\n", file->getFileName(), ELL_ERROR);
        png_destroy_read_struct(&png_ptr, NULL, NULL);
        return 0;
    }

    // for proper error handling
    if (setjmp(png_jmpbuf(png_ptr)))
    {
        png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
        if (RowPointers)
            delete [] RowPointers;
        return 0;
    }

    // changed by zola so we don't need to have public FILE pointers
    png_set_read_fn(png_ptr, file, user_read_data_fcn);

    png_set_sig_bytes(png_ptr, 8); // Tell png that we read the signature

    png_read_info(png_ptr, info_ptr); // Read the info section of the png file

    // Extract info
    png_get_IHDR(png_ptr, info_ptr,
                 (png_uint_32*)&Width, (png_uint_32*)&Height,
                 &BitDepth, &ColorType, NULL, NULL, NULL);

    // Convert palette color to true color
    if (ColorType==PNG_COLOR_TYPE_PALETTE)
        png_set_palette_to_rgb(png_ptr);

    // Convert low bit colors to 8 bit colors
    if (BitDepth < 8)
    {
        if (ColorType==PNG_COLOR_TYPE_GRAY || ColorType==PNG_COLOR_TYPE_GRAY_ALPHA)
            png_set_gray_1_2_4_to_8(png_ptr);
        else
            png_set_packing(png_ptr);
    }

    if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS))
        png_set_tRNS_to_alpha(png_ptr);

    // Convert high bit colors to 8 bit colors
    if (BitDepth == 16)
        png_set_strip_16(png_ptr);

    // Convert gray color to true color
    if (ColorType==PNG_COLOR_TYPE_GRAY || ColorType==PNG_COLOR_TYPE_GRAY_ALPHA)
        png_set_gray_to_rgb(png_ptr);

    // Update the changes
    png_read_update_info(png_ptr, info_ptr);
    png_get_IHDR(png_ptr, info_ptr,
                 (png_uint_32*)&Width, (png_uint_32*)&Height,
                 &BitDepth, &ColorType, NULL, NULL, NULL);

    // Convert RGBA to BGRA
    if (ColorType==PNG_COLOR_TYPE_RGB_ALPHA)
    {
#ifdef __BIG_ENDIAN__
        png_set_swap_alpha(png_ptr);
#else
//.........这里部分代码省略.........
开发者ID:jivibounty,项目名称:irrlicht,代码行数:101,代码来源:CImageLoaderPNG.cpp

示例7: printf

int ImageFormatPNG::load(const char *name, int& width, int& height, int& format) {
 	printf("ImageFormatPNG::load\n");

    // Open File
 	FILE* file = fopen(name,"rb");
 	if (file == 0) {
        printf("ImageFormatPNG::load(): can't open file '%s'\n",name);
 		return 0;
 	}

    // init width / height / format value to 0
    width  = 0;
 	height = 0;
    format = 0;
    
 	//Allocate a buffer of 8 bytes, where we can put the file signature.
    png_byte sig[8];

    //Read the 8 bytes from the file into the sig buffer.
    fread((char*)sig, sizeof(png_byte), 8, file);
 	if(!png_check_sig(sig,8)) {
 		fclose(file);
 		return 0;
 	}

 	//Here we create the png read struct.
 	png_structp pngPtr = png_create_read_struct(PNG_LIBPNG_VER_STRING, 0, 0, 0);
 	if(pngPtr == 0) {
 		fclose(file);
 		return 0;
 	}

 	//Here we create the png info struct.
 	png_infop infoPtr = png_create_info_struct(pngPtr);
 	if(infoPtr == 0) {
 		png_destroy_read_struct(&pngPtr, (png_infopp)0, (png_infopp)0);
 		fclose(file);
 		return 0;
 	}

 	png_set_read_fn(pngPtr,file, file_read_function);

    //Set the amount signature bytes we've already read:
    png_set_sig_bytes(pngPtr, 8);

    //Now call png_read_info with our pngPtr as image handle, and infoPtr to receive the file info.
    png_read_info(pngPtr, infoPtr);

    png_uint_32 imgWidth =  png_get_image_width(pngPtr, infoPtr);
    png_uint_32 imgHeight = png_get_image_height(pngPtr, infoPtr);

    //bits per CHANNEL! note: not per pixel!
    png_uint_32 bitdepth   = png_get_bit_depth(pngPtr, infoPtr);
    //Number of channels
    png_uint_32 channels   = png_get_channels(pngPtr, infoPtr);
    //Color type. (RGB, RGBA, Luminance, luminance alpha... palette... etc)
    png_uint_32 color_type = png_get_color_type(pngPtr, infoPtr);

    switch (color_type) {
        case PNG_COLOR_TYPE_PALETTE:
            png_set_palette_to_rgb(pngPtr);
            //Don't forget to update the channel info (thanks Tom!)
            //It's used later to know how big a buffer we need for the image
            channels = 3;
            break;
        case PNG_COLOR_TYPE_GRAY:
            if (bitdepth < 8)
                png_set_expand_gray_1_2_4_to_8(pngPtr);
            //And the bitdepth info
            bitdepth = 8;
        break;
    }

    /*if the image has a transperancy set.. convert it to a full Alpha channel..*/
    if (png_get_valid(pngPtr, infoPtr, PNG_INFO_tRNS)) {
        png_set_tRNS_to_alpha(pngPtr);
        channels+=1;
    }

    //We don't support 16 bit precision.. so if the image Has 16 bits per channel
    //precision... round it down to 8.
    if (bitdepth == 16)
        png_set_strip_16(pngPtr);

    //Array of row pointers. One for every row.
    png_bytep*  rowPtrs = new png_bytep[imgHeight];

    width = imgWidth;
    height = imgHeight;
    format = bitdepth * channels / 8;
    
    int data_decoded_size = width * height * format;
    
    // raw data image container
    unsigned char * img_data_decoded = new unsigned char[data_decoded_size];
    memset(img_data_decoded,0x00,data_decoded_size + 1);
    
	int stride = width * format;
    
    for (size_t i = 0; i < imgHeight; i++) {
//.........这里部分代码省略.........
开发者ID:wolfviking0,项目名称:image.js,代码行数:101,代码来源:ImageFormat.cpp

示例8: memcpy

bool BitmapData::initWithPNGData(const unsigned char *data, ssize_t size) {
    
    static const int PNGSIGSIZE = 8;
    
    png_byte        header[PNGSIGSIZE] = {0};
    png_structp     png_ptr     = 0;
    png_infop       info_ptr    = 0;
    
    memcpy(header, data, PNGSIGSIZE);
    if (png_sig_cmp(header, 0, PNGSIGSIZE) != 0) {
        return false;
    }
    
    png_ptr  = png_create_read_struct(PNG_LIBPNG_VER_STRING, 0, 0, 0);
    info_ptr = png_create_info_struct(png_ptr);
    setjmp(png_jmpbuf(png_ptr));
    
    
    PngSource pngSource;
    pngSource.data    = (unsigned char*)data;
    pngSource.size    = size;
    pngSource.offset  = 0;
    png_set_read_fn(png_ptr, &pngSource, pngReadCallback);
    
    png_read_info(png_ptr, info_ptr);
    _width = png_get_image_width(png_ptr, info_ptr);
    _height = png_get_image_height(png_ptr, info_ptr);
    png_byte bit_depth = png_get_bit_depth(png_ptr, info_ptr);
    png_uint_32 color_type = png_get_color_type(png_ptr, info_ptr);
    
    if (color_type == PNG_COLOR_TYPE_PALETTE) {
        png_set_palette_to_rgb(png_ptr);
    }
    if (color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8) {
        bit_depth = 8;
    }
    if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) {
        png_set_tRNS_to_alpha(png_ptr);
    }
    if (bit_depth == 16) {
        png_set_strip_16(png_ptr);
    }
    if (bit_depth < 8) {
        png_set_packing(png_ptr);
    }
    // update info
    png_read_update_info(png_ptr, info_ptr);
    bit_depth  = png_get_bit_depth(png_ptr, info_ptr);
    color_type = png_get_color_type(png_ptr, info_ptr);
    
    switch (color_type) {
        case PNG_COLOR_TYPE_GRAY:
            _renderFormat = Texture2D::PixelFormat::I8;
            break;
        case PNG_COLOR_TYPE_GRAY_ALPHA:
            _renderFormat = Texture2D::PixelFormat::AI88;
            break;
        case PNG_COLOR_TYPE_RGB:
            _renderFormat = Texture2D::PixelFormat::RGB888;
            break;
        case PNG_COLOR_TYPE_RGB_ALPHA:
            _renderFormat = Texture2D::PixelFormat::RGBA8888;
            break;
        default:
            break;
    }
    
    // read png data
    png_size_t rowbytes;
    png_bytep* row_pointers = (png_bytep*)malloc(sizeof(png_bytep) * _height);
    rowbytes = png_get_rowbytes(png_ptr, info_ptr);
    
    _dataSize = rowbytes * _height;
    _data = static_cast<unsigned char*>(malloc(_dataSize * sizeof(unsigned char)));
    
    if(!_data) {
        if (row_pointers != nullptr) {
            free(row_pointers);
        }
        return false;
    }
    
    for (unsigned short i = 0; i < _height; ++i) {
        row_pointers[i] = _data + i*rowbytes;
    }
    
    png_read_image(png_ptr, row_pointers);
    png_read_end(png_ptr, nullptr);
    
    if (color_type == PNG_COLOR_TYPE_RGB_ALPHA) {
        _alpha = true;
    } else {
        _alpha = false;
    }
    
    if (row_pointers != nullptr) {
        free(row_pointers);
    }
    
    if (png_ptr) {
//.........这里部分代码省略.........
开发者ID:BobLChen,项目名称:opengl-es-2d-3d,代码行数:101,代码来源:BitmapData.cpp

示例9: Pegas_log_info

	uint8_t* GraphicsTexture::loadImage()
	{
		Pegas_log_info("GraphicsTexture::loadImage");

		Resource::AutoDispose autoDispose(mResource);
		if (mResource.open() != STATUS_OK)
		{
			Pegas_log_error("mResource.open failed");
			return NULL;
		}

		png_byte header[8];
		if (mResource.read(header, sizeof(header)) != STATUS_OK)
		{
			Pegas_log_error("mResource.read failed");
			return NULL;
		}

		if (png_sig_cmp(header, 0, 8) != 0)
		{
			Pegas_log_error("png_sig_cmp failed, header param: %s", header);
			return NULL;
		}

		png_structp pngMain = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
		if (!pngMain) {
			Pegas_log_error("png_create_read_struct failed");
			return NULL;
		}
		png_infop pngInfo = png_create_info_struct(pngMain);
		if (!pngInfo) {
			Pegas_log_error("png_create_info_struct failed");
			return NULL;
		}
		png_set_read_fn(pngMain, &mResource, callback_read);
		if (setjmp(png_jmpbuf(pngMain))) {
			Pegas_log_error("setjmp failed");
			return NULL;
		}
		png_set_sig_bytes(pngMain, 8);
		png_read_info(pngMain, pngInfo);
		png_int_32 depth, colorType;
		png_uint_32 width, height;
		png_get_IHDR(pngMain, pngInfo, &width, &height, &depth, &colorType, NULL,
				NULL, NULL);
		mWidth = width;
		mHeight = height;
		bool transparency = false;
		// Creates a full alpha channel if transparency is encoded as
		// an array of palette entries or a single transparent color.
		if (png_get_valid(pngMain, pngInfo, PNG_INFO_tRNS)) {
			png_set_tRNS_to_alpha(pngMain);
			transparency = true;

			Pegas_log_error("png_get_valid failed");
			return NULL;
		}
		// Expands PNG with less than 8bits per channel to 8bits.
		if (depth < 0) {
			png_set_packing(pngMain);
			// Shrinks PNG with 16bits per color channel down to 8bits.
		} else if (depth == 16) {
			png_set_strip_16(pngMain);
		}

		// Indicates that image needs conversion to RGBA if	needed.
		switch (colorType) {
		case PNG_COLOR_TYPE_PALETTE:
			png_set_palette_to_rgb(pngMain);
			mFormat = transparency ? GL_RGBA : GL_RGB;
			break;
		case PNG_COLOR_TYPE_RGB:
			mFormat = transparency ? GL_RGBA : GL_RGB;
			break;
		case PNG_COLOR_TYPE_RGBA:
			mFormat = GL_RGBA;
			break;
		case PNG_COLOR_TYPE_GRAY:
			png_set_expand_gray_1_2_4_to_8(pngMain);
			mFormat = transparency ? GL_LUMINANCE_ALPHA : GL_LUMINANCE;
			break;
		case PNG_COLOR_TYPE_GA:
			png_set_expand_gray_1_2_4_to_8(pngMain);
			mFormat = GL_LUMINANCE_ALPHA;
			break;
		}
		png_read_update_info(pngMain, pngInfo);
		png_int_32 rowSize = png_get_rowbytes(pngMain, pngInfo);
		if (rowSize <= 0) {
			Pegas_log_error("invalid png row size: %d", rowSize);
			return NULL;
		}
		png_byte* imageBuffer = new png_byte[rowSize * height];
		if (!imageBuffer) {
			Pegas_log_error("can not allocate image buffer");
			return NULL;
		}
		png_bytep* rowPtrs = new png_bytep[height];
		if (!rowPtrs) {
			Pegas_log_error("can not allocate row pointers");
//.........这里部分代码省略.........
开发者ID:merelalkar,项目名称:zlpacman,代码行数:101,代码来源:GraphicsTexture.cpp

示例10: LoadPngData

static HPDF_STATUS
LoadPngData  (HPDF_Dict     image,
              HPDF_Xref     xref,
              HPDF_Stream   png_data,
              HPDF_BOOL     delayed_loading)

{
	HPDF_STATUS ret = HPDF_OK;
	png_uint_32 width, height;
	int bit_depth, color_type;
	png_structp png_ptr = NULL;
	png_infop info_ptr = NULL;

	HPDF_PTRACE ((" HPDF_Image_LoadPngImage\n"));

	/* create read_struct. */
	png_ptr = png_create_read_struct (PNG_LIBPNG_VER_STRING,
			image->error, PngErrorFunc, NULL);

	if (png_ptr == NULL) {
		HPDF_SetError (image->error, HPDF_FAILD_TO_ALLOC_MEM, 0);
		return HPDF_FAILD_TO_ALLOC_MEM;
	}

	/* create info-struct */
	info_ptr = png_create_info_struct (png_ptr);

	if (info_ptr == NULL) {
		HPDF_SetError (image->error, HPDF_FAILD_TO_ALLOC_MEM, 0);
		goto Exit;
	}

	png_set_sig_bytes (png_ptr, HPDF_PNG_BYTES_TO_CHECK);
	png_set_read_fn (png_ptr, (void *)png_data, (png_rw_ptr)&PngReadFunc);

	/* reading info structure. */
	png_read_info(png_ptr, info_ptr);
	if (image->error->error_no != HPDF_OK) {
		goto Exit;
	}

	png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, NULL, NULL, NULL);

	/* 16bit images are not supported. */
	if (bit_depth == 16) {
		png_set_strip_16(png_ptr);
	}

	png_read_update_info(png_ptr, info_ptr);
	if (image->error->error_no != HPDF_OK) {
		goto Exit;
	}

	/* check palette-based images for transparent areas and load them immediately if found */
	if (xref && PNG_COLOR_TYPE_PALETTE & color_type) {
		png_bytep trans;
		int num_trans;
		HPDF_Dict smask;
		png_bytep smask_data;

		if (!png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS) ||
			!png_get_tRNS(png_ptr, info_ptr, &trans, &num_trans, NULL)) {
			goto no_transparent_color_in_palette;
		}

		smask = HPDF_DictStream_New (image->mmgr, xref);
		if (!smask) {
			ret = HPDF_FAILD_TO_ALLOC_MEM;
			goto Exit;
		}

		smask->header.obj_class |= HPDF_OSUBCLASS_XOBJECT;
		ret = HPDF_Dict_AddName (smask, "Type", "XObject");
		ret += HPDF_Dict_AddName (smask, "Subtype", "Image");
		ret += HPDF_Dict_AddNumber (smask, "Width", (HPDF_UINT)width);
		ret += HPDF_Dict_AddNumber (smask, "Height", (HPDF_UINT)height);
		ret += HPDF_Dict_AddName (smask, "ColorSpace", "DeviceGray");
		ret += HPDF_Dict_AddNumber (smask, "BitsPerComponent", (HPDF_UINT)bit_depth);

		if (ret != HPDF_OK) {
			HPDF_Dict_Free(smask);
			ret = HPDF_INVALID_PNG_IMAGE;
			goto Exit;
		}

		smask_data = HPDF_GetMem(image->mmgr, width * height);
		if (!smask_data) {
			HPDF_Dict_Free(smask);
			ret = HPDF_FAILD_TO_ALLOC_MEM;
			goto Exit;
		}

		if (ReadTransparentPaletteData(image, png_ptr, info_ptr, smask_data, trans, num_trans) != HPDF_OK) {
			HPDF_FreeMem(image->mmgr, smask_data);
			HPDF_Dict_Free(smask);
			ret = HPDF_INVALID_PNG_IMAGE;
			goto Exit;
		}

		if (HPDF_Stream_Write(smask->stream, smask_data, width * height) != HPDF_OK) {
//.........这里部分代码省略.........
开发者ID:bitfactory-software,项目名称:libharu,代码行数:101,代码来源:hpdf_image_png.c

示例11: rwpng_read_image24_libpng

pngquant_error rwpng_read_image24_libpng(FILE *infile, png24_image *mainprog_ptr)
{
    png_structp  png_ptr = NULL;
    png_infop    info_ptr = NULL;
    png_size_t   rowbytes;
    int          color_type, bit_depth;

    png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, mainprog_ptr,
      rwpng_error_handler, NULL);
    if (!png_ptr) {
        return PNG_OUT_OF_MEMORY_ERROR;   /* out of memory */
    }

    info_ptr = png_create_info_struct(png_ptr);
    if (!info_ptr) {
        png_destroy_read_struct(&png_ptr, NULL, NULL);
        return PNG_OUT_OF_MEMORY_ERROR;   /* out of memory */
    }

    /* setjmp() must be called in every function that calls a non-trivial
     * libpng function */

    if (setjmp(mainprog_ptr->jmpbuf)) {
        png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
        return LIBPNG_FATAL_ERROR;   /* fatal libpng error (via longjmp()) */
    }

    struct rwpng_read_data read_data = {infile, 0};
    png_set_read_fn(png_ptr, &read_data, user_read_data);

    png_read_info(png_ptr, info_ptr);  /* read all PNG info up to image data */


    /* alternatively, could make separate calls to png_get_image_width(),
     * etc., but want bit_depth and color_type for later [don't care about
     * compression_type and filter_type => NULLs] */

    png_get_IHDR(png_ptr, info_ptr, &mainprog_ptr->width, &mainprog_ptr->height,
      &bit_depth, &color_type, NULL, NULL, NULL);


    /* expand palette images to RGB, low-bit-depth grayscale images to 8 bits,
     * transparency chunks to full alpha channel; strip 16-bit-per-sample
     * images to 8 bits per sample; and convert grayscale to RGB[A] */

    /* GRR TO DO:  preserve all safe-to-copy ancillary PNG chunks */

    if (!(color_type & PNG_COLOR_MASK_ALPHA)) {
#ifdef PNG_READ_FILLER_SUPPORTED
        png_set_expand(png_ptr);
        png_set_filler(png_ptr, 65535L, PNG_FILLER_AFTER);
#else
        fprintf(stderr, "pngquant readpng:  image is neither RGBA nor GA\n");
        png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
        mainprog_ptr->retval = 26;
        return mainprog_ptr->retval;
#endif
    }
/*
    if (color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8)
        png_set_expand(png_ptr);
    if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS))
        png_set_expand(png_ptr);
 */
    if (bit_depth == 16)
        png_set_strip_16(png_ptr);

    if (color_type == PNG_COLOR_TYPE_GRAY ||
        color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
        png_set_gray_to_rgb(png_ptr);


    /* get and save the gamma info (if any) for writing */

    double gamma;
    mainprog_ptr->gamma = png_get_gAMA(png_ptr, info_ptr, &gamma) ? gamma : 0.45455;

    png_set_interlace_handling(png_ptr);

    /* all transformations have been registered; now update info_ptr data,
     * get rowbytes and channels, and allocate image memory */

    png_read_update_info(png_ptr, info_ptr);

    rowbytes = png_get_rowbytes(png_ptr, info_ptr);

    if ((mainprog_ptr->rgba_data = malloc(rowbytes*mainprog_ptr->height)) == NULL) {
        fprintf(stderr, "pngquant readpng:  unable to allocate image data\n");
        png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
        return PNG_OUT_OF_MEMORY_ERROR;
    }

    png_bytepp row_pointers = rwpng_create_row_pointers(info_ptr, png_ptr, mainprog_ptr->rgba_data, mainprog_ptr->height, 0);

    /* now we can go ahead and just read the whole image */

    png_read_image(png_ptr, row_pointers);

    /* and we're done!  (png_read_end() can be omitted if no processing of
     * post-IDAT text/time/etc. is desired) */
//.........这里部分代码省略.........
开发者ID:cheoree,项目名称:pngquant,代码行数:101,代码来源:rwpng.c

示例12: png_create_read_struct

//
// Reads the image
//
void PNGReader::read(ImageFile * image)
{
	volatile unsigned char ** volatile rowPointers = NULL;
	png_struct * pngPtr = NULL;
	png_info * infoPtr = NULL;
	byte * data = NULL;

	try
	{
		int colorType, bitDepth;
		bool hasAlpha = false;
		uint bytesPerElement;
		ImageFormat format;
		unsigned long w, h;
		unsigned rowbytes;

		// Initialize the PNG library
		pngPtr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, pngErrorFunc, pngWarningFunc);
		if (unlikely(!pngPtr))
			throw Exception(QString("%1: png_create_read_struct() failed").arg(m_File.fileName()));

		// Initialize the PNG info struct
		infoPtr = png_create_info_struct(pngPtr);
		if (unlikely(!infoPtr))
			throw Exception(QString("%1: png_create_info_struct() failed").arg(m_File.fileName()));

		// Setup error handler
		if (unlikely(setjmp(png_jmpbuf(pngPtr)) != 0))
			throw Exception(QString("%1: PNG decompression failed").arg(m_File.fileName()));

		// Setup file reading
		png_set_read_fn(pngPtr, &m_File, pngReadFunc);
		png_set_sig_bytes(pngPtr, 8);
		png_read_info(pngPtr, infoPtr);
		png_get_IHDR(pngPtr, infoPtr, &w, &h, &bitDepth, &colorType, NULL, NULL, NULL);

		// Setup 16 bit -> 8 bit conversion
		if (bitDepth > 8) 
			png_set_strip_16(pngPtr);

		// Translate transparency to alpha channel
  		if (png_get_valid(pngPtr, infoPtr, PNG_INFO_tRNS))
		{
			png_set_tRNS_to_alpha(pngPtr);
			hasAlpha = true;
		}

		// Setup gamma correction
		double gamma;
		if (png_get_gAMA(pngPtr, infoPtr, &gamma))
			png_set_gamma(pngPtr, 2.2, gamma);
		else
			png_set_gamma(pngPtr, 2.2, 0.45455);

		// We want at least 8-bit
		if (bitDepth < 8)
		{
			if ((colorType == PNG_COLOR_TYPE_GRAY || colorType == PNG_COLOR_TYPE_GRAY_ALPHA))
				png_set_gray_1_2_4_to_8(pngPtr);
			else
				png_set_packing(pngPtr);
		}

		// Convert paletted images to RGB
		if (colorType == PNG_COLOR_TYPE_PALETTE)
		{
			png_set_palette_to_rgb(pngPtr);
			colorType = hasAlpha ? PNG_COLOR_TYPE_RGBA : PNG_COLOR_TYPE_RGB;
		}

		// Convert gray/alpha images to RGB
		if (colorType == PNG_COLOR_TYPE_GRAY_ALPHA ||
			(colorType == PNG_COLOR_TYPE_GRAY && hasAlpha))
		{
			png_set_gray_to_rgb(pngPtr);
			colorType = PNG_COLOR_TYPE_RGB_ALPHA;
		}

		// Add dummy alpha channel for RGB images
		if (colorType == PNG_COLOR_TYPE_RGB && !hasAlpha)
		{
			png_set_filler(pngPtr, 0xFF, PNG_FILLER_BEFORE);
			hasAlpha = true;
		}
		else if (colorType == PNG_COLOR_TYPE_RGB_ALPHA)
			hasAlpha = true;

		// Select pixel format
		switch (colorType)
		{
		case PNG_COLOR_TYPE_PALETTE:
		case PNG_COLOR_TYPE_GRAY_ALPHA:
			Q_ASSERT(false);	// Should be handled in the code above
			break;

		case PNG_COLOR_TYPE_GRAY:
			bytesPerElement = 1;
//.........这里部分代码省略.........
开发者ID:ashuron,项目名称:superplex3d_prototype,代码行数:101,代码来源:png_reader.cpp

示例13: PyObject_AsFileDescriptor

PyObject*
_png_module::_read_png(const Py::Object& py_fileobj, const bool float_result)
{
    png_byte header[8];   // 8 is the maximum size that can be checked
    FILE* fp = NULL;
    bool close_file = false;

#if PY3K
    int fd = PyObject_AsFileDescriptor(py_fileobj.ptr());
    PyErr_Clear();
#endif

    if (py_fileobj.isString())
    {
        std::string fileName = Py::String(py_fileobj);
        const char *file_name = fileName.c_str();
        if ((fp = fopen(file_name, "rb")) == NULL)
        {
            throw Py::RuntimeError(
                Printf("Could not open file %s for reading", file_name).str());
        }
        close_file = true;
    }
#if PY3K
    else if (fd != -1) {
        fp = fdopen(fd, "r");
    }
#else
    else if (PyFile_CheckExact(py_fileobj.ptr()))
    {
        fp = PyFile_AsFile(py_fileobj.ptr());
    }
#endif
    else
    {
        PyObject* read_method = PyObject_GetAttrString(py_fileobj.ptr(), "read");
        if (!(read_method && PyCallable_Check(read_method)))
        {
            Py_XDECREF(read_method);
            throw Py::TypeError("Object does not appear to be a 8-bit string path or a Python file-like object");
        }
        Py_XDECREF(read_method);
    }

    if (fp)
    {
        if (fread(header, 1, 8, fp) != 8)
        {
            throw Py::RuntimeError(
                "_image_module::readpng: error reading PNG header");
        }
    }
    else
    {
        _read_png_data(py_fileobj.ptr(), header, 8);
    }
    if (png_sig_cmp(header, 0, 8))
    {
        throw Py::RuntimeError(
            "_image_module::readpng: file not recognized as a PNG file");
    }

    /* initialize stuff */
    png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);

    if (!png_ptr)
    {
        throw Py::RuntimeError(
            "_image_module::readpng:  png_create_read_struct failed");
    }

    png_infop info_ptr = png_create_info_struct(png_ptr);
    if (!info_ptr)
    {
        throw Py::RuntimeError(
            "_image_module::readpng:  png_create_info_struct failed");
    }

    if (setjmp(png_jmpbuf(png_ptr)))
    {
        throw Py::RuntimeError(
            "_image_module::readpng:  error during init_io");
    }

    if (fp)
    {
        png_init_io(png_ptr, fp);
    }
    else
    {
        png_set_read_fn(png_ptr, (void*)py_fileobj.ptr(), &read_png_data);
    }
    png_set_sig_bytes(png_ptr, 8);
    png_read_info(png_ptr, info_ptr);

    png_uint_32 width = png_get_image_width(png_ptr, info_ptr);
    png_uint_32 height = png_get_image_height(png_ptr, info_ptr);

    int bit_depth = png_get_bit_depth(png_ptr, info_ptr);

//.........这里部分代码省略.........
开发者ID:wrgiannjr,项目名称:matplotlib,代码行数:101,代码来源:_png.cpp

示例14: png_create_read_struct_2


//.........这里部分代码省略.........
      return (NULL);
   }
#ifdef USE_FAR_KEYWORD
   png_memcpy(png_ptr->jmpbuf, jmpbuf, png_sizeof(jmp_buf));
#endif
#endif /* PNG_SETJMP_SUPPORTED */

#ifdef PNG_USER_MEM_SUPPORTED
   png_set_mem_fn(png_ptr, mem_ptr, malloc_fn, free_fn);
#endif

   png_set_error_fn(png_ptr, error_ptr, error_fn, warn_fn);

   if (user_png_ver)
   {
      i = 0;
      do
      {
         if (user_png_ver[i] != png_libpng_ver[i])
            png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
      } while (png_libpng_ver[i++]);
    }
    else
         png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;


    if (png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH)
    {
       /* Libpng 0.90 and later are binary incompatible with libpng 0.89, so
       * we must recompile any applications that use any older library version.
       * For versions after libpng 1.0, we will be compatible, so we need
       * only check the first digit.
       */
      if (user_png_ver == NULL || user_png_ver[0] != png_libpng_ver[0] ||
          (user_png_ver[0] == '1' && user_png_ver[2] != png_libpng_ver[2]) ||
          (user_png_ver[0] == '0' && user_png_ver[2] < '9'))
      {
#if defined(PNG_STDIO_SUPPORTED) && !defined(_WIN32_WCE)
         char msg[80];
         if (user_png_ver)
         {
           png_snprintf(msg, 80,
              "Application was compiled with png.h from libpng-%.20s",
              user_png_ver);
           png_warning(png_ptr, msg);
         }
         png_snprintf(msg, 80,
             "Application  is  running with png.c from libpng-%.20s",
             png_libpng_ver);
         png_warning(png_ptr, msg);
#endif
#ifdef PNG_ERROR_NUMBERS_SUPPORTED
         png_ptr->flags = 0;
#endif
         png_error(png_ptr,
            "Incompatible libpng version in application and library");
      }
   }

   /* Initialize zbuf - compression buffer */
   png_ptr->zbuf_size = PNG_ZBUF_SIZE;
   png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
     (png_uint_32)png_ptr->zbuf_size);
   png_ptr->zstream.zalloc = png_zalloc;
   png_ptr->zstream.zfree = png_zfree;
   png_ptr->zstream.opaque = (voidpf)png_ptr;

      switch (inflateInit(&png_ptr->zstream))
      {
         case Z_OK: /* Do nothing */ break;
         case Z_MEM_ERROR:
         case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory error");
            break;
         case Z_VERSION_ERROR: png_error(png_ptr, "zlib version error");
            break;
         default: png_error(png_ptr, "Unknown zlib error");
      }


   png_ptr->zstream.next_out = png_ptr->zbuf;
   png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;

   png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL);

#ifdef PNG_SETJMP_SUPPORTED
/* Applications that neglect to set up their own setjmp() and then
   encounter a png_error() will longjmp here.  Since the jmpbuf is
   then meaningless we abort instead of returning. */
#ifdef USE_FAR_KEYWORD
   if (setjmp(jmpbuf))
       PNG_ABORT();
   png_memcpy(png_ptr->jmpbuf, jmpbuf, png_sizeof(jmp_buf));
#else
   if (setjmp(png_ptr->jmpbuf))
       PNG_ABORT();
#endif
#endif /* PNG_SETJMP_SUPPORTED */

   return (png_ptr);
}
开发者ID:18702515007xjy,项目名称:cocos2d,代码行数:101,代码来源:pngread.c

示例15: LoadImage

void LoadImage (const char *filename, unsigned char **pic, int *width, int *height)
{
    png_byte** row_pointers;
    unsigned char *fbuffer = NULL;
    png_bytep p_fbuffer;

    int nLen = g_FileSystemTable.m_pfnLoadFile( (char *)filename, (void **)&fbuffer, 0 );
    if (nLen == -1)
        return;

    p_fbuffer = fbuffer;

    // the reading glue
    // http://www.libpng.org/pub/png/libpng-manual.html

    png_structp png_ptr = png_create_read_struct
                          (PNG_LIBPNG_VER_STRING, png_voidp_NULL,
                           user_error_fn, user_warning_fn);
    if (!png_ptr)
    {
        g_FuncTable.m_pfnSysPrintf ("libpng error: png_create_read_struct\n");
        return;
    }

    png_infop info_ptr = png_create_info_struct(png_ptr);
    if (!info_ptr) {
        png_destroy_read_struct(&png_ptr,
                                png_infopp_NULL, png_infopp_NULL);
        g_FuncTable.m_pfnSysPrintf ("libpng error: png_create_info_struct (info_ptr)\n");
        return;
    }

    png_infop end_info = png_create_info_struct(png_ptr);
    if (!end_info) {
        png_destroy_read_struct(&png_ptr, &info_ptr,
                                png_infopp_NULL);
        g_FuncTable.m_pfnSysPrintf ("libpng error: png_create_info_struct (end_info)\n");
        return;
    }

    // configure the read function
    png_set_read_fn(png_ptr, (voidp)&p_fbuffer, (png_rw_ptr)&user_read_data);

    if (setjmp(png_ptr->jmpbuf)) {
        png_destroy_read_struct(&png_ptr, &info_ptr,
                                &end_info);
        if (*pic)
        {
            g_free(*pic);
            free(row_pointers);
        }
        return;
    }

    png_read_info(png_ptr, info_ptr);

    int bit_depth = png_get_bit_depth(png_ptr, info_ptr);
    int color_type = png_get_color_type(png_ptr, info_ptr);

    // we want to treat all images the same way
    //   The following code transforms grayscale images of less than 8 to 8 bits,
    //   changes paletted images to RGB, and adds a full alpha channel if there is
    //   transparency information in a tRNS chunk.
    if (color_type == PNG_COLOR_TYPE_PALETTE)
        png_set_palette_to_rgb(png_ptr);

    if (color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8)
        png_set_gray_1_2_4_to_8(png_ptr);

    if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS))
        png_set_tRNS_to_alpha(png_ptr);

    if ( ! ( color_type & PNG_COLOR_MASK_ALPHA ) ) {
        // Set the background color to draw transparent and alpha images over.
        png_color_16 my_background, *image_background;

        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);

        // Add alpha byte after each RGB triplet
        png_set_filler(png_ptr, 0xff, PNG_FILLER_AFTER);
    }

    // read the sucker in one chunk
    png_read_update_info(png_ptr, info_ptr);

    color_type = png_get_color_type(png_ptr, info_ptr);
    bit_depth = png_get_bit_depth(png_ptr, info_ptr);

    *width = png_get_image_width(png_ptr, info_ptr);
    *height = png_get_image_height(png_ptr, info_ptr);

    // allocate the pixel buffer, and the row pointers
    int size = (*width)*(*height)*4;
    // still have to use that g_malloc heresy
    *pic = (unsigned char *)g_malloc(size);
//.........这里部分代码省略.........
开发者ID:AEonZR,项目名称:GtkRadiant,代码行数:101,代码来源:plugin.cpp


注:本文中的png_set_read_fn函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。