Beispiel #1
0
static int load_image(at_bitmap *image, FILE *stream, at_input_opts_type * opts, at_exception_type * exp) 
{
	png_structp png;
	png_infop info, end_info;
	png_bytep *rows;
	unsigned short width, height, row;
	int pixel_size;
	int result = 1;
	
	if (!init_structs(&png, &info, &end_info, exp)) 
	  return 0;

	png_init_io(png, stream);
	CHECK_ERROR();
	
	rows = read_png(png, info, opts);

	width = (unsigned short)png_get_image_width(png, info);
	height = (unsigned short)png_get_image_height(png, info);
	if ( png_get_color_type(png, info) == PNG_COLOR_TYPE_GRAY ) {
		pixel_size = 1;
	} else {
		pixel_size = 3;
	}

	*image = at_bitmap_init(NULL, width, height, pixel_size);
	for ( row = 0 ; row < height ; row++, rows++ ) {
		memcpy(AT_BITMAP_PIXEL(image, row, 0), *rows,
		       width * pixel_size * sizeof(unsigned char));
	}
 cleanup:
	finalize_structs(png, info, end_info);
	return result;
}
Beispiel #2
0
/****************************************************************************
 * M A I N ( )
 ****************************************************************************/
int main(int argc, char * argv[])
{
	int rc;

	if(argc == 1) {
		print_usage(argv[0]);
		print_bugreport();
		printf("Error! You must supply a filename\n");
		return ERROR;
	}

	if(!strcmp("-h", argv[1]) ||
		!strcmp("--help", argv[1])) {
			print_usage(argv[0]);
			print_help();
			return 0;
		}

	if(!strcmp("-v", argv[1]) ||
		!strcmp("--version", argv[1])) {
			version();
			return 0;
		}

	if(argc > 2) {
		printf("Skipping extra arguments on commandline\n\n");
	}

	version();
	rc = read_png(argv[1]);
	return rc;
}
Beispiel #3
0
int VFrame::read_png(const unsigned char *data)
{
	long img_sz =
		((long)data[0] << 24) | ((long)data[1] << 16) |
		((long)data[2] << 8)  |  (long)data[3];
	return read_png(data+4, img_sz);
}
Beispiel #4
0
static int perform_one_test ( FILE *fp, int nfiles ) {
    int i;
    struct timespec before, after;

    /* Clear out all errors: */
    rewind ( fp );

    if ( mytime ( &before ) ) {
        for ( i=0; i<nfiles; ++i ) {
            if ( read_png ( fp ) ) {
                if ( ferror ( fp ) ) {
                    perror ( "temporary file" );
                    fprintf ( stderr, "file %d: error reading PNG data\n", i );
                    return 0;
                }
            }

            else {
                perror ( "temporary file" );
                fprintf ( stderr, "file %d: error from libpng\n", i );
                return 0;
            }
        }
    }

    else
        return 0;

    if ( mytime ( &after ) ) {
        /* Work out the time difference and print it - this is the only output,
         * so flush it immediately.
         */
        unsigned long s = after.tv_sec - before.tv_sec;
        long ns = after.tv_nsec - before.tv_nsec;

        if ( ns < 0 ) {
            --s;
            ns += 1000000000;

            if ( ns < 0 ) {
                fprintf ( stderr, "timepng: bad clock from kernel\n" );
                return 0;
            }
        }

        printf ( "%lu.%.9ld\n", s, ns );
        fflush ( stdout );
        if ( ferror ( stdout ) ) {
            fprintf ( stderr, "timepng: error writing output\n" );
            return 0;
        }

        /* Successful return */
        return 1;
    }

    else
        return 0;
}
Matrix<Color> read_img(std::string filename)
{
    std::size_t n = filename.size();
    std::string extension3 = filename.substr(n-3, n);
    std::string extension4 = filename.substr(n-4, n);
    if(!extension3.compare("bmp"))
    {
        return read_bmp(filename);
    }
    else if(!extension3.compare("gif"))
    {
        return read_gif(filename);
    }
    else if(!extension3.compare("ico"))
    {
        return read_ico(filename);
    }
    /*else if(!extension3.compare("jpg"))
    {
        return read_jpeg(filename);
    }*/
    else if(!extension3.compare("pcx"))
    {
        return read_pcx(filename);
    }
    else if(!extension3.compare("png"))
    {
        return read_png(filename);
    }
    else if(!extension3.compare("pbm"))
    {
        return bw2colorimage(read_pbm(filename));
    }
    else if(!extension3.compare("pgm"))
    {
        return gray2colorimage(read_pgm(filename));
    }
    else if(!extension3.compare("ppm"))
    {
        return read_ppm(filename);
    }
    else if(!extension3.compare("tga"))
    {
        return read_tga(filename);
    }
    else if(!extension4.compare("tiff"))
    {
        return read_tiff(filename);
    }
    else
    {
        return Matrix<Color>();
    }
}
Beispiel #6
0
void GenericImage::load(const char* filename)
{
    const char *ext = filename + strlen(filename) - 4;
   
    if (!strcmp(ext, ".png") || !strcmp(ext, ".PNG"))
        read_png(filename);
    else if (!strcmp(ext, ".jpg") || !strcmp(ext, ".JPG"))
        read_jpg(filename);
//    else if (!strcmp(ext, ".raw") || !strcmp(ext, ".RAW"))
//        read_raw(filename);
    else fail("only support jpeg and png image format\n");
}
Beispiel #7
0
static void
parse_images(const char* logoFilename, const char* logoBaseName,
	const char* iconsFilename, const char* iconsBaseName)
{
	int logoWidth;
	int logoHeight;
	png_bytep* logoRowPtrs = NULL;
	png_structp logoPngPtr;
	png_infop logoInfoPtr;

	int iconsWidth;
	int iconsHeight;
	png_bytep* iconsRowPtrs = NULL;
	png_structp iconsPngPtr;
	png_infop iconsInfoPtr;

	read_png(logoFilename, logoWidth, logoHeight, logoRowPtrs, logoPngPtr,
		logoInfoPtr);
	read_png(iconsFilename, iconsWidth, iconsHeight, iconsRowPtrs, iconsPngPtr,
		iconsInfoPtr);

	// write 24-bit images
	write_24bit_image(logoBaseName, logoWidth, logoHeight, logoRowPtrs);
	write_24bit_image(iconsBaseName, iconsWidth, iconsHeight, iconsRowPtrs);

	// write 8-bit index color images
	create_8bit_images(logoBaseName, logoWidth, logoHeight, logoRowPtrs,
		iconsBaseName, iconsWidth, iconsHeight, iconsRowPtrs);

	// free resources
	png_destroy_read_struct(&logoPngPtr, &logoInfoPtr, NULL);
	for (int y = 0; y < logoHeight; y++)
		free(logoRowPtrs[y]);
	free(logoRowPtrs);

	png_destroy_read_struct(&iconsPngPtr, &iconsInfoPtr, NULL);
	for (int y = 0; y < iconsHeight; y++)
		free(iconsRowPtrs[y]);
	free(iconsRowPtrs);
}
Beispiel #8
0
int load_block(unsigned char** block, unsigned* width, unsigned* height, const char* fname, const int base_img_size)
{
	FILE* file = fopen(fname, "rb");

	if (file != NULL) {
		read_png(block, width, height, file, base_img_size);
		fclose(file);
	} else {
		perror("Error:");
	}

	return file != NULL;
}
Beispiel #9
0
static int process_file(const char *fname)
{
	image image;
	image.file_name = fname;
	int result;
	gradient g;

	result = read_png(fname, &image, &g);

	if(result)
		print_css_gradient(image.file_name, g);

	return result;
}
int main(int argc, char **argv)
{

    if(argc < 2){
        fprintf(stderr, "Usage: %s <png>\n", argv[0]);
        return EXIT_FAILURE;
    }

    if(read_png(argv[1]) != OK){
        fprintf(stderr, "Error reading png\n");
        return EXIT_FAILURE;
    }

    return 0;
}
unicap_status_t ucil_load_png( char *filename, unicap_data_buffer_t *buffer )
{
   FILE *f;
   
   if( !check_if_png( filename, &f ) )
   {
      TRACE( "File '%s' is not a valid PNG image\n", filename );
      return STATUS_FAILURE;
   }
   
   if( read_png( f, PNG_BYTES_TO_CHECK, buffer ) < 0 )
   {
      TRACE( "File '%s' could not be loaded\n", filename );
      return STATUS_FAILURE;
   }
   
   return STATUS_SUCCESS;
}
Beispiel #12
0
void json_parse_opttexture(jsonvalue json, image3f*& txt, string name) {
    if(not json.object_contains(name)) return;
    auto filename = json.object_element(name).as_string();
    if(filename.empty()) { txt = nullptr; return; }
    auto dirname = json_texture_paths.back();
    auto fullname = dirname + filename;
    if (json_texture_cache.find(fullname) == json_texture_cache.end()) {
        auto ext = fullname.substr(fullname.size()-3);
        if(ext == "pfm") {
            auto image = read_pnm("models/pisa_latlong.pfm", true);
            image = image.gamma(1/2.2);
            json_texture_cache[fullname] = new image3f(image);
        } else if(ext == "png") {
            auto image = read_png(fullname,true);
            json_texture_cache[fullname] = new image3f(image);
        } else error("unsupported image format %s\n", ext.c_str());
    }
    txt = json_texture_cache[fullname];
}
Beispiel #13
0
int main() {

	// open png image
	struct rgba8* image;
	uint32_t width;
	uint32_t height;

	read_png("img/img_01.png", (uint8_t**)&image, &width, &height);
	// ----

	// convert to yui
	int y_bits = 6;
	int uv_bits = 6;
	int uv_down = 1;

	size_t yui_data_size = 0;
	uint8_t* yui_data = yui_encode(image, yui_RGBA8, width, height, y_bits, uv_bits, uv_down, &yui_data_size);

	free(image);

	// save yui file
	FILE *fp;

	fp = fopen("img/img_01.yui", "w");
	fwrite(yui_data, 1, yui_data_size, fp);

	fclose(fp);

	//free(yui_data);
	// ----

	// save png file
	image = yui_decode(yui_data, yui_data_size, yui_RGBA8, (uint16_t*)&width, (uint16_t*)&height);
	free(yui_data);

	//write_png("img/2.png", (uint8_t*)image, width, height);

	//free(image);
	// ----

	return 1;
}
Beispiel #14
0
/**
 * Load image
 * Parameters:
 *      path:   input path 
 *      mem:    memory for decoding
 * Return:
 *           0  OK
 *          -1  ERROR
 */
int loadImage (const char *path, Bitmap_t *mem) 
{
    VALIDATE_NOT_NULL2 (path, mem);
    const char const *postfix = getFilePostfix (path);
    if (NULL == postfix) {
        LogE ("Failed getFilePostfix in loadImage\n");
        return -1;
    }

    if (strcasecmp (postfix, "jpg") == 0) {
        return read_jpeg (path, mem);
    }
    else if (strcasecmp (postfix, "png") == 0) {
        return read_png (path, mem);
    }
    else {
        LogE ("Invalid postfix name (%s) in loadImage\n", postfix);
        return -1;
    }
}
Beispiel #15
0
struct texture *
load_texture_from_png(const char *filename)
{
	struct texture *newtexture;
	unsigned int width, height;
	int type;
	unsigned char *data;

	if((newtexture = get_texture_with_name(filename)))
		return newtexture;

	data = (unsigned char *)read_png(filename, &width, &height, &type);
	if(!data) {
		fprintf(stderr, "Error: Couldn't load texture %s\n", filename);
		return NULL;
	}

	newtexture = create_texture_structure();
	if(!newtexture)
		return NULL;

	snprintf(newtexture->name, 256, "%s", filename);
	newtexture->gl_num = curr_gl_num++;
	newtexture->width = width;
	newtexture->height = height;

	glBindTexture(GL_TEXTURE_2D, newtexture->gl_num);
	glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
	glTexImage2D(GL_TEXTURE_2D, 0, 3, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data);

	free(data);

	return newtexture;
}
Beispiel #16
0
	bool next_frame()
	{
		png_structp png_ptr;
		png_infop info_ptr;
		struct archive_entry *ae;
		int res;

read_data:
		res = archive_read_next_header(this->archive, &ae); 
		if (res != ARCHIVE_OK || res == ARCHIVE_EOF) {
			if (play_mode == LOOP) {
				/* Go to the first archive entry and read it. */
				close();
				open();
				goto read_data;
			} else {
				printf("Animation finished.\n");
				return false;
			}
		} else if (res == ARCHIVE_FATAL || res == ARCHIVE_WARN || res == ARCHIVE_RETRY) {
			printf("Failed to read next header.\n");
			return false;
		} else if (res == 0) {
			/* At the end of the archive check the loop flag to see if we
			 * restart. */
			if (read_png(&png_ptr, &info_ptr, this->archive) == 1) {
				fprintf(stderr, "Problem reading PNG.\n");
				return false;
			}	
			/* Store the image data into the framebuffer. */
			set_framebuffer(png_ptr, info_ptr, framebuffer);
			png_destroy_read_struct(&png_ptr, png_infopp_NULL, png_infopp_NULL);
		} else {
			fprintf(stderr, "archive_read_next_header resulted in an unknown error.\n");
			return false;
		}	
		return true;
	}
Beispiel #17
0
void gl_init(){
  glClearColor( .5, .5, .5, 0 );
  
  glEnable(GL_TEXTURE_2D); // Enable texturing
  glGenTextures(1, &textureID); // Generate a unique texture ID
  glBindTexture(GL_TEXTURE_2D, textureID); // Activate the texture
  
  png_data_t *image = read_png("texture.png");
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  glTexImage2D(GL_TEXTURE_2D, 
               0, 
               image->has_alpha ? GL_RGBA : GL_RGB,
               image->width,
               image->height, 
               0, 
               image->has_alpha ? GL_RGBA : GL_RGB,
               GL_UNSIGNED_BYTE,
               image->pixelData);

  
}
Beispiel #18
0
int main()
{
	gdImagePtr im, im2;

	im = gdImageCreateTrueColor(400, 400);

	if (!im) {
		fprintf(stderr, "Can't create 400x400 TC image\n");
		return 1;
	}

	gdImageFilledRectangle(im, 19, 29, 390, 390, 0xFFFFFF);
	gdImageRectangle(im, 19, 29, 390, 390, 0xFF0000);
	save_png(im, "a1.png");

	im2 = gdImageCropAuto(im, GD_CROP_SIDES);
	if (im2) {
		save_png(im2, "a2.png");
		gdImageDestroy(im2);
	}
	gdImageDestroy(im);

	im = read_png("test_crop_threshold.png");
	if (!im) {
		return 1;
	}

	im2 = gdImageCropThreshold(im, 0xFFFFFF, 0.6);
	if (im2) {
		save_png(im2, "a4.png");
		gdImageDestroy(im2);
	}

	gdImageDestroy(im);
	return 0;
}
Beispiel #19
0
int main(int argc, char * argv[])
{
	webp::vp8l::huffman_io::init_array();
	std::string input;
	std::string output;
	bool encode = false;
	bool decode = false;
	for(++argv; argv[0]; ++argv){
		if (argv[0] == std::string("-d"))
			decode = true;
		else
		if (argv[0] == std::string("-e"))
			encode = true;
		else
		if (argv[0] == std::string("-h")){
			print_help();
			return 0;
		}
		else{
			if (input.size() == 0)
				input = argv[0];
			else if (output.size() == 0)
				output = argv[0];
			else{
				printf("What you mean? %s\n", argv[0]);
				print_help();
				return 1;
			}
		}
	}

	if ((encode && decode) || (!encode && !decode)){
		printf("Specify key -d or -e\n");
		print_help();
		return 1;
	}
	if (input.size() == 0){
		printf("Specify input file name\n");
		print_help();
		return 1;
	}
	if (output.size() == 0){
		printf("Specify output file name\n");
		print_help();
		return 1;
	}

	try{
		if (decode){
			webp::WebP_DECODER webp(input);
			webp.save2png(output);
			return 0;
		}
		if (encode){
			image_t image;
			read_png(input, image);
			webp::WebP_ENCODER encoder(image.image, image.width, image.height, output);
			return 0;
		}
	}
	catch(webp::exception::Exception & e){
		std::cout << e.message << std::endl;
	}
	return 0;
}
Beispiel #20
0
static gboolean gst_gcs_set_caps(GstBaseTransform * btrans, GstCaps * incaps, GstCaps * outcaps) 
{
  GstGcs *gcs = GST_GCS (btrans);
  gint in_width, in_height;
  gint out_width, out_height;
  
  GST_GCS_LOCK (gcs);
  
  gst_video_format_parse_caps(incaps, &gcs->in_format, &in_width, &in_height);
  gst_video_format_parse_caps(outcaps, &gcs->out_format, &out_width, &out_height);
  if (!(gcs->in_format == gcs->out_format) || 
      !(in_width == out_width && in_height == out_height)) {
    GST_WARNING("Failed to parse caps %" GST_PTR_FORMAT " -> %" GST_PTR_FORMAT, incaps, outcaps);
    GST_GCS_UNLOCK (gcs);
    return FALSE;
  }
  
  gcs->width  = in_width;
  gcs->height = in_height;
  
  GST_INFO("Initialising Gcs...");
  gst_pad_set_event_function(GST_BASE_TRANSFORM_SINK_PAD(gcs),  gst_gcs_sink_event);

  const CvSize size = cvSize(gcs->width, gcs->height);
  GST_WARNING (" width %d, height %d", gcs->width, gcs->height);

  //////////////////////////////////////////////////////////////////////////////
  // allocate image structs in all spaces///////////////////////////////////////
  gcs->pImageRGBA    = cvCreateImageHeader(size, IPL_DEPTH_8U, 4);

  gcs->pImgRGB       = cvCreateImage(size, IPL_DEPTH_8U, 3);
  gcs->pImgScratch   = cvCreateImage(size, IPL_DEPTH_8U, 3);

  gcs->pImgGRAY      = cvCreateImage(size, IPL_DEPTH_8U, 1);
  gcs->pImgGRAY_copy = cvCreateImage(size, IPL_DEPTH_8U, 1);
  gcs->pImgGRAY_diff = cvCreateImage(size, IPL_DEPTH_8U, 1);
  gcs->pImgGRAY_1    = cvCreateImage(size, IPL_DEPTH_8U, 1);
  gcs->pImgGRAY_1copy= cvCreateImage(size, IPL_DEPTH_8U, 1);
  cvZero( gcs->pImgGRAY_1 );
  cvZero( gcs->pImgGRAY_1copy );

  gcs->pImgChA       = cvCreateImageHeader(size, IPL_DEPTH_8U, 1);
  gcs->pImgCh1       = cvCreateImage(size, IPL_DEPTH_8U, 1);
  gcs->pImgCh2       = cvCreateImage(size, IPL_DEPTH_8U, 1);
  gcs->pImgCh3       = cvCreateImage(size, IPL_DEPTH_8U, 1);
  gcs->pImgChX       = cvCreateImage(size, IPL_DEPTH_8U, 1);

  gcs->pImg_skin     = cvCreateImage(size, IPL_DEPTH_8U, 1);

  gcs->grabcut_mask   = cvCreateMat( size.height, size.width, CV_8UC1);
  cvZero(gcs->grabcut_mask);
  initialise_grabcut( &(gcs->GC), gcs->pImgRGB, gcs->grabcut_mask );
  gcs->bbox_prev      = cvRect( 60,70, 210, 170 );

  //////////////////////////////////////////////////////////////////////////////
#ifdef KMEANS
  // k-means allocation ////////////////////////////////////////////////////////
  gcs->pImgRGB_kmeans  = cvCreateImage(size, IPL_DEPTH_8U, 3);
  gcs->num_samples     = size.height * size.width;
  gcs->kmeans_points   = cvCreateMat( gcs->num_samples, 5, CV_32FC1);
  gcs->kmeans_clusters = cvCreateMat( gcs->num_samples, 1, CV_32SC1);
#endif //KMEANS

  //////////////////////////////////////////////////////////////////////////////
  // Init ghost file ///////////////////////////////////////////////////////////
  curlMemoryStructGCS  chunk;
  //gchar url[]="file:///home/mcasassa/imco2/mods/gstreamer/cyclops/shaders/mask8.png";
  //gchar url[]="file:///apps/devnfs/mcasassa/mask_320x240.png";
  char curlErrBuf[255];
  
  if( gcs->ghostfilename){
    if(FALSE == curl_download(gcs->ghostfilename, "", &chunk, curlErrBuf)) {
      GST_ERROR("download failed, err: %s", curlErrBuf);
    }
    
    char errBuf[255];
    if( FALSE == read_png(&chunk, &(gcs->raw_image), &(gcs->info), errBuf)){
      GST_ERROR("png load failed, err: %s", errBuf);
    }

    const CvSize sizegh = cvSize(gcs->info.width, gcs->info.height);
    gcs->cvGhost = cvCreateImageHeader(sizegh, IPL_DEPTH_8U, gcs->info.channels);
    gcs->cvGhost->imageData = (char*)gcs->raw_image;

    gcs->cvGhostBw = cvCreateImage(sizegh, IPL_DEPTH_8U, 1);
    if( gcs->info.channels > 1){
      cvCvtColor( gcs->cvGhost, gcs->cvGhostBw, CV_RGB2GRAY );
    }
    else{
      cvCopy(gcs->cvGhost, gcs->cvGhostBw, NULL);
    }

    gcs->cvGhostBwResized = cvCreateImage(size, IPL_DEPTH_8U, 1);
    cvResize( gcs->cvGhostBw, gcs->cvGhostBwResized, CV_INTER_LINEAR);

    gcs->cvGhostBwAffined = cvCreateImage(size, IPL_DEPTH_8U, 1);
  }

  GST_INFO(" Collected caps, image in size (%dx%d), ghost size (%dx%d) %dch",gcs->width, gcs->height,
            gcs->info.width, gcs->info.height, gcs->info.channels );

  // 3 points of the face bbox associated to the ghost.
  gcs->srcTri[0].x = 145;
  gcs->srcTri[0].y = 74;
  gcs->srcTri[1].x = 145;
  gcs->srcTri[1].y = 74+39;
  gcs->srcTri[2].x = 145+34;
  gcs->srcTri[2].y = 74+39;

  gcs->warp_mat = cvCreateMat(2,3,CV_32FC1);


  gcs->numframes = 0;

  GST_INFO("Gcs initialized.");
  
  GST_GCS_UNLOCK (gcs);
  
  return TRUE;
}
Beispiel #21
0
int
main(void)
{
   /* Exit code 0 on success. */
   return !read_png(stdin);
}
Beispiel #22
0
static void
update_display(struct display *dp)
   /* called once after the first read to update all the info, original_pp and
    * original_ip must have been filled in.
    */
{
   png_structp pp;
   png_infop   ip;

   /* Now perform the initial read with a 0 tranform. */
   read_png(dp, &dp->original_file, "original read", 0/*no transform*/);

   /* Move the result to the 'original' fields */
   dp->original_pp = pp = dp->read_pp, dp->read_pp = NULL;
   dp->original_ip = ip = dp->read_ip, dp->read_ip = NULL;

   dp->original_rowbytes = png_get_rowbytes(pp, ip);
   if (dp->original_rowbytes == 0)
      display_log(dp, LIBPNG_BUG, "png_get_rowbytes returned 0");

   dp->chunks = png_get_valid(pp, ip, 0xffffffff);
   if ((dp->chunks & PNG_INFO_IDAT) == 0) /* set by png_read_png */
      display_log(dp, LIBPNG_BUG, "png_read_png did not set IDAT flag");

   dp->original_rows = png_get_rows(pp, ip);
   if (dp->original_rows == NULL)
      display_log(dp, LIBPNG_BUG, "png_read_png did not create row buffers");

   if (!png_get_IHDR(pp, ip,
      &dp->width, &dp->height, &dp->bit_depth, &dp->color_type,
      &dp->interlace_method, &dp->compression_method, &dp->filter_method))
      display_log(dp, LIBPNG_BUG, "png_get_IHDR failed");

   /* 'active' transforms are discovered based on the original image format;
    * running one active transform can activate others.  At present the code
    * does not attempt to determine the closure.
    */
   {
      png_uint_32 chunks = dp->chunks;
      int active = 0, inactive = 0;
      int ct = dp->color_type;
      int bd = dp->bit_depth;
      unsigned int i;

      for (i=0; i<TTABLE_SIZE; ++i)
      {
         int transform = transform_info[i].transform;

         if ((transform_info[i].valid_chunks == 0 ||
               (transform_info[i].valid_chunks & chunks) != 0) &&
            (transform_info[i].color_mask_required & ct) == 
               transform_info[i].color_mask_required &&
            (transform_info[i].color_mask_absent & ct) == 0 &&
            (transform_info[i].bit_depths & bd) != 0 &&
            (transform_info[i].when & TRANSFORM_R) != 0)
            active |= transform;

         else if ((transform_info[i].when & TRANSFORM_R) != 0)
            inactive |= transform;
      }

      /* Some transforms appear multiple times in the table; the 'active' status
       * is the logical OR of these and the inactive status must be adjusted to
       * take this into account.
       */
      inactive &= ~active;

      dp->active_transforms = active;
      dp->ignored_transforms = inactive; /* excluding write-only transforms */

      if (active == 0)
         display_log(dp, INTERNAL_ERROR, "bad transform table");
   }
}
Beispiel #23
0
VFrame::VFrame(unsigned char *png_data, long image_size)
{
	reset_parameters(1);
	params = new BC_Hash;
	read_png(png_data, image_size);
}
Beispiel #24
0
int main(int argc, char **argv) {

    int ret, tmp;
    img_t img;
    char *output_dir;
    FILE *out_file;

    if (argc < 5) {
        printf("Usage:\npacked_tilegen <input> <output_dir> <tileX> <tileY> [cardinal direction N|E|S|W\n");
        exit(1);
    }

    printf("Read file \"%s\"\n", argv[1]);
    if (strstr(argv[1], ".png"))
        ret = read_png(argv[1], &img);
    else if (strstr(argv[1], ".ppm"))
        ret = read_ppm(argv[1], &img);
    else {
        printf("Unknown format!\n");
        exit(2);
    }

    output_dir = argv[2];

    if (ret) {
        printf("Could not read png input file! %d\n", ret);
        exit(ret);
    }

    img.tileX = atoi(argv[3]);
    img.tileY = atoi(argv[4]);

    if (argc > 5) {
        switch(argv[5][0]) {
        case 'n':
        case 'N':
            // keep defaults
            break;
        case 'e':
        case 'E':
            tmp = img.tileX;
            img.tileX = img.tileY;
            img.tileY = (2<<12) - 1 - tmp;
            break;
        case 's':
        case 'S':
            img.tileX = (2<<12) - 1 - img.tileX;
            img.tileY = (2<<12) - 1 - img.tileY;
            break;
        case 'w':
        case 'W':
            tmp = img.tileX;
            img.tileX = (2<<12) - 1 - img.tileY;
            img.tileY = tmp;
            break;
        default:
            fprintf(stderr, "Unknown cardinal direction \"%s\". Default to north\n", argv[5]);
        }
    }

    // create pack file for writing
    out_file = open_packed_file(output_dir, img.tileX, img.tileY);
    tmp = 0;

    while (1) {

        // crop image at given zoom level..
        crop_image(&img, tmp++, out_file);

        scale_image(&img);

        if (img.sizeX == TILE_SIZE) {
            save_image(&img, output_dir);
            break;
        }
    }

    close_packed_file(out_file);

    return 0;
}
Beispiel #25
0
int
read_image(const char *filename, int *width, int *height, 
	   unsigned char *rgb)
{
    char buf[4];
    unsigned char *ubuf = (unsigned char *) buf;
    int success = 0;

    FILE *file;
    file = fopen(filename, "rb");
    if (file == NULL) return(0);
  
    /* see what kind of file we have */

    fread(buf, 1, 4, file);
    fclose(file);

    if (!strncmp("BM", buf, 2))
    {
        success = read_bmp(filename, width, height, rgb);
    }
    else if (!strncmp("GIF8", buf, 4))
    {
#ifdef HAVE_LIBGIF
        success = read_gif(filename, width, height, rgb);
#else
        fprintf(stderr, 
                "Sorry, this program was not compiled with GIF support\n");
        success = 0;
#endif /* HAVE_LIBGIF */
    }
    else if ((ubuf[0] == 0xff) && (ubuf[1] == 0xd8))
    {
#ifdef HAVE_LIBJPEG
        success = read_jpeg(filename, width, height, rgb);
#else
        fprintf(stderr, 
                "Sorry, this program was not compiled with JPEG support\n");
        success = 0;
#endif /* HAVE_LIBJPEG */
    }
    else if ((ubuf[0] == 0x89) && !strncmp("PNG", buf+1, 3))
    {
#ifdef HAVE_LIBPNG
        success = read_png(filename, width, height, rgb);
#else
        fprintf(stderr, 
                "Sorry, this program was not compiled with PNG support\n");
        success = 0;
#endif /* HAVE_LIBPNG */
    }
    else if ((   !strncmp("P6\n", buf, 3))
             || (!strncmp("P5\n", buf, 3))
             || (!strncmp("P4\n", buf, 3))
             || (!strncmp("P3\n", buf, 3))
             || (!strncmp("P2\n", buf, 3))
             || (!strncmp("P1\n", buf, 3)))
    {
#ifdef HAVE_LIBPNM
        success = read_pnm(filename, width, height, rgb);
#else
        fprintf(stderr, 
                "Sorry, this program was not compiled with PNM support\n");
        success = 0;
#endif /* HAVE_LIBPNM */
    }
    else if (((!strncmp ("MM", buf, 2)) && (ubuf[2] == 0x00) 
              && (ubuf[3] == 0x2a))
             || ((!strncmp ("II", buf, 2)) && (ubuf[2] == 0x2a) 
                 && (ubuf[3] == 0x00)))
    {
#ifdef HAVE_LIBTIFF
        success = read_tiff(filename, width, height, rgb);
#else
        fprintf(stderr, 
                "Sorry, this program was not compiled with TIFF support\n");
        success = 0;
#endif
    }
    else
    {
        fprintf(stderr, "Unknown image format\n");
        success = 0;
    }

    return(success);
}
Beispiel #26
0
/* perform the actual conversion from png to gba formats */
void png2gba(FILE* in, FILE* out, char* name, int palette,
        int tileize, char* colorkey) {

    /* load the image */
    struct Image* image = read_png(in);

    /* write preamble stuff */
    fprintf(out, "/* %s.h\n * generated by png2gba program */\n\n", name);
    fprintf(out, "#define %s_width %d\n", name, image->w);
    fprintf(out, "#define %s_height %d\n\n", name, image->h);
    if (palette) {
        fprintf(out, "const unsigned char %s_data [] = {\n", name);
    } else {
        fprintf(out, "const unsigned short %s_data [] = {\n", name); 
    }

    /* the palette stores up to PALETTE_SIZE colors */
    unsigned short color_palette[PALETTE_SIZE];

    /* palette sub 0 is reserved for transparent color */
    unsigned char palette_size = 1;

    /* clear the palette */
    memset(color_palette, 0, PALETTE_SIZE * sizeof(unsigned short));

    /* insert the transparent color */
    unsigned short ckey = hex24_to_15(colorkey);
    color_palette[0] = ckey; 

    /* loop through the pixel data */
    unsigned char red, green, blue;
    int colors_this_line = 0;
    png_byte* ptr;

    while ((ptr = next_byte(image, tileize))) {
        red = ptr[0];
        green = ptr[1];
        blue = ptr[2];

        /* convert to 16-bit color */
        unsigned short color = (blue >> 3) << 10;
        color += (green >> 3) << 5;
        color += (red >> 3);

        /* print leading space if first of line */
        if (colors_this_line == 0) {
            fprintf(out, "    ");
        }

        /* print color directly, or palette index */
        if (!palette) { 
            fprintf(out, "0x%04X", color);
        } else {
            unsigned char index = insert_palette(color, color_palette,
                    &palette_size);
            fprintf(out, "0x%02X", index);
        }

        fprintf(out, ", ");

        /* increment colors on line unless too many */
        colors_this_line++;
        if ((palette && colors_this_line >= MAX_ROW8) ||
                (!palette && colors_this_line >= MAX_ROW16)) {
            fprintf(out, "\n");
            colors_this_line = 0;
        } 
    }

    /* write postamble stuff */
    fprintf(out, "\n};\n\n");

    /* write the palette if needed */
    if (palette) {
        int colors_this_line = 0;
        fprintf(out, "const unsigned short %s_palette [] = {\n", name); 
        int i;
        for (i = 0; i < PALETTE_SIZE; i++) {
            if (colors_this_line == 0) {
                fprintf(out, "    "); 
            }
            fprintf(out, "0x%04x", color_palette[i]);
            if (i != (PALETTE_SIZE - 1)) {
                fprintf(out, ", ");
            }
            colors_this_line++;
            if (colors_this_line > 8) {
                fprintf(out, "\n");
                colors_this_line = 0;
            }
        }
        fprintf(out, "\n};\n\n");
    }

    /* close up, we're done */
    fclose(out);
}
Beispiel #27
0
int read_frame(int number, TFrame *frame)
{
  char filename[MAX_NAME_LEN];
  int errcode;
  int i, j;
  float factor;

  frame->time = 0.0;

  if(input_format == FORMAT_IPX) { /* IPX VIDEO FORMAT */
    /* IPX code reads in a single frame and converts to floats */
    if(IPX_read_frame(number, frame, &ipx_read_status)) {
      printf("Error: Could not read frame %d from IPX file %s\n", number, input_template);
      exit(1);
    }
    
  }else { /* A SET OF FRAME STILLS */

    /* Get the filename */
    sprintf(filename, input_template, number);

    /* Read the data in raw format */

    errcode = 0;
    switch(input_format) {
    case FORMAT_BMP: {
      errcode = read_bmp(filename, &readraw);
      break;
    }
    case FORMAT_PNG: {
      errcode = read_png(filename, &readraw);
      break;
    }
    default: {
      errcode = IO_ERROR_FORMAT;
    }
    }
    
    /* Check error code */
    
    if(errcode) {
      switch(errcode) {
      case IO_ERROR_OPEN: {
	printf("Error: Could not open input file %s\n", filename);
	break;
      }
      case IO_ERROR_FORMAT: {
	printf("Error: Input file %s has an invalid file format\n", filename);
	break;
      }
      case IO_ERROR_SIZE: {
	printf("Error: Size of frame %s different to previous frames\n", filename);
	break;
      }
      case IO_ERROR_OTHER: {
	printf("Error: Could not read input file %s\n", filename);
	break;
      }
      }
      exit(1);
    }
    
    /* Check/Allocate the frame */

    /* Check if the frame has been allocated */
    if(frame->allocated) {
      /* Data already allocated - check same size */
      if((frame->width != readraw.width) || (frame->height != readraw.height)) {
	/* This should never happen - checked already */
	printf("\n====== OUT OF CHEESE ERROR =========\n");
	exit(1);
      }
      
    }else {
      /* Allocate memory. Note organised in COLUMNS */
      frame->data = (float**) malloc(sizeof(float*)*readraw.width);
      for(i=0;i!=readraw.width;i++)
	frame->data[i] = (float*) malloc(sizeof(float)*readraw.height);
      frame->width = readraw.width;
      frame->height = readraw.height;
      frame->allocated =  1;
    }

    /* Change the data to be floating point between 0 and 1 */
    
    factor = (float) ((1 << readraw.bpp) - 1) ;
  
    if(readraw.channels != 1) {
      /* Input frame is in color */
      if(readraw.bpp > 8) {
	printf("\nSorry: Cannot read color images with bpp > 8 yet\n");
	exit(1);
      }else {
	/* Convert red channel */
	for(i=0;i<frame->width;i++) {
	  for(j=0;j<frame->height;j++) {
	    frame->data[i][j] = ((float) readraw.data[j][readraw.channels*i]) / factor;
	  }
	}
      }
    }else {
      /* Greyscale image */
      if(readraw.bpp > 16) {
	printf("\nSorry: Cannot read greyscale images > 16bpp yet\n");
	exit(1);
      }else if(readraw.bpp > 8) {
	/* Data has 2 bytes per pixel */
	for(i=0;i<frame->width;i++) {
	  for(j=0;j<frame->height;j++) {
	    frame->data[i][j] = ( 256.0*((float) readraw.data[j][2*i]) + 
				  ((float) readraw.data[j][2*i+1]) ) / factor;
	  }
	}
      }else {
	/* if less than 8 bit, data must be unpacked into one byte per pixel */
	for(i=0;i<frame->width;i++) {
	  for(j=0;j<frame->height;j++) {
	    frame->data[i][j] = ((float) readraw.data[j][i]) / factor;
	  }
	}
      }
    }
  }

  frame->number = number;
  
  return(0);
}
Beispiel #28
0
VFrame::VFrame(unsigned char *png_data)
{
	reset_parameters(1);
	params = new BC_Hash;
	read_png(png_data);
}
Beispiel #29
0
int main(int argc, char* argv[])
{
  int error;
  FT_Face face;
  FILE *fp;
  const wchar_t* str1 = L"위대한 younwook 연욱대왕 만만세~";

  DrawBuffer *drawBuffer;

  int x, y, width, height;
  width = 300; 
  height = 300;

  setlocale(LC_ALL, "ko_KR.UTF-8");

  printf("test\n\n");
  wprintf( L"유니코드 입력 가능 여부 확인\n" );

  error = FT_Init_FreeType( &ftlib );
  if( error ) {
    printf( "FT_Init_FreeType error occurred!\n" );
  }

  /* Load a font face */
  error = FT_New_Face( ftlib, 
		       // "/usr/share/fonts/truetype/unfonts/UnTaza.ttf",
		       "/System/Library/Fonts/AppleGothic.ttf",
		       0,
		       &face );
  if( error == FT_Err_Unknown_File_Format ) {
    printf( "font format is not supported!! \n" );
  } else if( error ) {
    printf( "Font file load failure!!! \n");
  }

  /* 픽셀 크기를 세팅하는 부분입니다. */
  error = FT_Set_Char_Size(
			   face,   /* handle to face object */
			   0,      /* char_width in 1/64th of points */
			   8*64,  /* char_height in 1/64th of points */
			   width,    /* horizontal device resolution */
			   height );  /* vertical device resolution */
  /*
    캐릭터의 높이와 너비는 1/64 포인트 단위로 정해집니다. 1 포인트는
    장치상에서 1/72 인치를 의미합니다. 만약 너비에 0을 세팅한다면 이는
    "캐릭터 높이와 같음" 을 의미하는 것입니다. 
  */
  if( error ) {
    printf( "Face size setting error occurred! \n" );
  }

  
  /*
    libpng 부분을 먼저 구현해 봅니다...
  */

  png_byte *data;

  // fp = fopen("in.png", "r");
  // if( !fp ) {
  //   printf( "file open error... \n" );
  //   return 0;
  // }
  drawBuffer = read_png("in.png");

  printf("tttt\n");

  // drawBuffer 변수를 생성한다. 
  // (사실 이 부분은 팩토리든 뭐든 사용해서 추상화시켜야 한다.)
  // drawBuffer.width = width;
  // drawBuffer.height = height;
  // drawBuffer.data = data;
  //
  //

  // 다시 freetype 부분으로 돌아옵니다. 
  FT_GlyphSlot slot = face->glyph;
  int pen_x, pen_y, n;
  char str[] = "test";
  unsigned char* test_buffer;
  FT_Bitmap_Size bitmap_size;
  int i, j, k;
  unsigned char p;

  pen_x = 300;
  pen_y = 200;
  error = FT_Select_Charmap( face, FT_ENCODING_UNICODE );

  wprintf( L"the char is %c, %d, %d \n", *str1,  *str1, wcslen(str1) );
  error = FT_Load_Glyph( face, 
			 FT_Get_Char_Index( face, *str1 ), // 0x00a9 ), 
			 FT_LOAD_RENDER );

  error = FT_Render_Glyph( face->glyph, FT_RENDER_MODE_NORMAL );
  if (error) {
    printf( "FT_Load_Glyph, FT_Render_Glyph error!!\n" );
    return 0;
  }
  
  printf("The bitmap size is %d, %d\n", slot->bitmap.width, slot->bitmap.rows);
  test_buffer = slot->bitmap.buffer;

  draw_string_line( face, drawBuffer, 50, 50, str1 ); 

  write_png("tt.png", drawBuffer);

  return 1;

}
Beispiel #30
0
/* decode hidim png file and write the torrent file */
int decode(const char *pngfilename) {
    FILE *fp;
    png_uint_32 height, width;
    png_bytep *row_pointers = NULL, *transpose = NULL;
    char *filename, *basefilename, *sha1sum;
    int start_row, start_column, line_length, c;
    unsigned int length, metadata_length, count, s;

    if ((fp = fopen(pngfilename, "rb")) == NULL) {
        fprintf(stderr, "%s: %s\n", pngfilename, strerror(errno));
        return 0;
    }
    if (config & CONFIG_VERBOSE) {
        printf(":: decoding %s\n", pngfilename);
    }

    if (!read_png(fp, &row_pointers, &width, &height)) {
        fclose(fp);
        fprintf(stderr, "Error: %s is not a png file.\n", pngfilename);
        return 0;
    }
    fclose(fp);

    /* rotate image */
    transpose = rotate_image(row_pointers, width, height);
    free_array(row_pointers, height);
    if (transpose == NULL) { // it can't be. already checked before
        exit(EXIT_FAILURE);
    }

    /* search for hidim key */
    if (!search_key(transpose, width, height, &start_row, &start_column)) {
        fprintf(stderr, "Error: %s is not a hidim or is corrupted.\n", pngfilename);
        free_array(transpose, width);
        return 0;
    } else if (config & CONFIG_MORE_VERBOSE) {
        printf("  hidim key found at (%d, %d)\n", start_row, (int)(height-start_column-1));
    }

    /* extract metadata */
    read_metadata(transpose, start_row, start_column, &line_length, &filename, &sha1sum, &metadata_length, &length);

    /* for security reason, only keep the basename of filename */
    basefilename = basename(filename);
    if (config & CONFIG_MORE_VERBOSE) {
        printf("==== metadata (%d bytes) ====\n", metadata_length);
        printf("  line_length: %d  sha1sum: %s  length: %d\n", line_length, sha1sum, length);
        printf("  filename   : %s\n", filename);
        printf("====\n");
        //printf(":: %d %s %s %d %d\n", line_length, basefilename, sha1sum, metadata_length, length);
    }
    /* get the torrent */
    unsigned char *torrent = calloc(length, sizeof(char));
    if (torrent == NULL) {
        fprintf(stderr, "Error: Can't allocate %d bytes.\n", length*sizeof(char));
        exit(EXIT_FAILURE);
    }

    count = c = s = 0;
    while (count < length+metadata_length) {
        if (count >= metadata_length) {
            torrent[count - metadata_length] = (unsigned char)transpose[start_row+s][3*start_column+c];
        }
        if (c == (line_length*3 -1) ) {
            c = 0;
            s++;
        } else {
            c++;
        }
        count++;
    }
    free_array(transpose, width);

    /* check the sha1sum of the torrent we extracted with sha1sum from metadata */
    unsigned char md[20];
    SHA1(torrent, length, md);
    char *sha1sum_comp = hexa_sha1sum(md);
    if (strcmp(sha1sum_comp, sha1sum) != 0) {
        if (config & CONFIG_MORE_VERBOSE) {
            printf("sha2sum: expected %s, got %s\n", sha1sum, sha1sum_comp);
        }
        fprintf(stderr, "%s: wrong sha1sum for extracted data.\n", filename);
        free(sha1sum_comp);
        free(sha1sum);
        free(torrent);
        free(filename);
        return 0;
    }
    free(sha1sum);
    free(sha1sum_comp);

    /* check if torrent file does not already exist */
    if (is_file(basefilename) && (!(config & CONFIG_OVERWRITE))) {
        fprintf(stderr, "%s already exists. nothing done.\n", basefilename);
        free(torrent);
        free(filename);
        return 0;
    }
    /* write torrent to file */
    FILE *fo = fopen(basefilename, "w");
    fwrite(torrent, sizeof(char), length, fo);
    fclose(fo);
    if (config & CONFIG_VERBOSE) {
        printf("%s has been saved.\n", basefilename);
    }

    free(torrent);
    free(filename);

    return 1;
}