/* function: "write_png(bmp, path[, color_type, text_dict])\n
Writes the bitmap as a png at the given path.\n
Raises OSError on failure.\n
\n
Optional parameters:\n
 - color_type: A constant from the png-module (e.g. png.RGB_ALPHA)\n
 - text_dict: A dictionary of key-strings to value-strings\n
   for png tEXt meta-data."
name: "write_png" */
static void write_png_py(const FilePath& p,
  const Bitmap& bmp,
  const Optional<int>& rawColorType,
  const Optional<png_tEXt_map>& maybeTextChunks)
{
  const auto defaultType = static_cast<int>(PngColorType::RGB_ALPHA);

  const auto colorType =
    to_enum<PngColorType>(rawColorType.Or(defaultType)).Visit(
      [](const PngColorType t){
        return t;
      },
      []() -> PngColorType{
        throw ValueError("color_type out of range.");
      });

  auto r = maybeTextChunks.Visit(
    [&](const png_tEXt_map& textChunks){
      return write_png(p, bmp, colorType, textChunks);
    },
    [&](){
      return write_png(p, bmp, colorType);
    });

  if (!r.Successful()){
    throw OSError(r.ErrorDescription());
  }
}
Exemplo n.º 2
0
boolean test_generation_callback(int generation, population *pop){
  double * img = (double *)pop->entity_iarray[0]->chromosome[0];
  int i;
  char buffer[1024];
  real support_threshold;
  for(i = 0;i<TSIZE(amp);i++){
    real_out->image[i] = sqrt(img[i]*img[i]+img[TSIZE(amp)+i]*img[TSIZE(amp)+i]);
  }
  printf("%d: fitness = %f\n",generation,pop->entity_iarray[0]->fitness);


  if(opts->iterations && opts->cur_iteration%opts->iterations == opts->iterations-1){
    sprintf(buffer,"real_out-%05d.png",opts->cur_iteration);
    write_png(real_out,buffer,COLOR_JET);
    
    freeimg(prev_support);
    prev_support = imgcpy(support);
    freeimg(support);      
    support_threshold = get_newsupport_level(real_out,&support_size,radius,&my_log,opts);
    my_log.threshold = support_threshold;
    if(support_threshold > 0){
      /*	support =  get_newsupport(real_out,support_threshold, radius,opts);*/
      support =  get_filtered_support(real_out,support_threshold, radius,opts);
    }else{
      if(opts->support_update_algorithm == REAL_ERROR_CAPPED){
	exit(0);
      }else{
	abort();
      }
    }
    if(opts->cur_iteration <= opts->iterations_to_min_blur){
      radius = get_blur_radius(opts);
    }
    if(/*opts->cur_iteration > 50 ||*/ (opts->automatic && opts->algorithm == RAAR && my_log.Ereal < 0.2)){
      stop++;
    }
    if(stop > stop_threshold){
      exit(0);
    }
    sprintf(buffer,"support-%05d.png",opts->cur_iteration);    
    write_png(support,buffer,COLOR_JET);
  }
  /* restore original amplitudes */
  for(i = 0;i<TSIZE(amp);i++){
    real_out->image[i] = norm(real_out,i);
  }


  opts->cur_iteration++;
  return TRUE;
}
Exemplo n.º 3
0
Arquivo: opengl.c Projeto: Dinth/naev
/**
 * @brief Takes a screenshot.
 *
 *    @param filename Name of the file to save screenshot as.
 */
void gl_screenshot( const char *filename )
{
   GLubyte *screenbuf;
   png_bytep *rows;
   int i, w, h;

   /* Allocate data. */
   w           = gl_screen.rw;
   h           = gl_screen.rh;
   screenbuf   = malloc( sizeof(GLubyte) * 3 * w*h );
   rows        = malloc( sizeof(png_bytep) * h );

   /* Read pixels from buffer -- SLOW. */
   glPixelStorei(GL_PACK_ALIGNMENT, 1); /* Force them to pack the bytes. */
   glReadPixels( 0, 0, w, h, GL_RGB, GL_UNSIGNED_BYTE, screenbuf );

   /* Convert data. */
   for (i = 0; i < h; i++)
      rows[i] = &screenbuf[ (h - i - 1) * (3*w) ];

   /* Save PNG. */
   write_png( filename, rows, w, h, PNG_COLOR_TYPE_RGB, 8);

   /* Check to see if an error occurred. */
   gl_checkErr();

   /* Free memory. */
   free( screenbuf );
   free( rows );
}
Exemplo n.º 4
0
int main(int argc, char *argv[])
{
    const int frame_w = 640;
    const int frame_h = 480;

    if (argc < 4) {
        printf("usage: %s <image file> <subtitle file> <time>\n", argv[0]);
        exit(1);
    }
    char *imgfile = argv[1];
    char *subfile = argv[2];
    double tm = strtod(argv[3], 0);

    init(frame_w, frame_h);
    ASS_Track *track = ass_read_file(ass_library, subfile, NULL);
    if (!track) {
        printf("track init failed!\n");
        return 1;
    }

    ASS_Image *img =
        ass_render_frame(ass_renderer, track, (int) (tm * 1000), NULL);
    image_t *frame = gen_image(frame_w, frame_h);
    blend(frame, img);

    ass_free_track(track);
    ass_renderer_done(ass_renderer);
    ass_library_done(ass_library);

    write_png(imgfile, frame);

    return 0;
}
Exemplo n.º 5
0
void write_img(PDF pdf, image_dict * idict)
{
    if (img_state(idict) < DICT_WRITTEN) {
        report_start_file(filetype_image, img_filepath(idict));
        switch (img_type(idict)) {
        case IMG_TYPE_PNG:
            write_png(pdf, idict);
            break;
        case IMG_TYPE_JPG:
            write_jpg(pdf, idict);
            break;
        case IMG_TYPE_JP2:
            write_jp2(pdf, idict);
            break;
        case IMG_TYPE_JBIG2:
            write_jbig2(pdf, idict);
            break;
        case IMG_TYPE_PDFMEMSTREAM:
        case IMG_TYPE_PDF:
            write_epdf(pdf, idict,(int) pdf_suppress_optional_info);
            break;
        case IMG_TYPE_PDFSTREAM:
            write_pdfstream(pdf, idict);
            break;
        default:
            normal_error("pdf backend","internal error: writing unknown image type");
        }
        report_stop_file(filetype_image);
        if (img_type(idict) == IMG_TYPE_PNG) {
            write_additional_png_objects(pdf);
        }
    }
    if (img_state(idict) < DICT_WRITTEN)
        img_state(idict) = DICT_WRITTEN;
}
Exemplo n.º 6
0
static int put_image(struct vf_instance *vf, mp_image_t *mpi, double pts)
{
    mp_image_t *dmpi = (mp_image_t *)mpi->priv;

    if(!(mpi->flags&(MP_IMGFLAG_DIRECT|MP_IMGFLAG_DRAW_CALLBACK))){
        dmpi=vf_get_image(vf->next,mpi->imgfmt,
                                    MP_IMGTYPE_EXPORT, 0,
                                    mpi->width, mpi->height);
        vf_clone_mpi_attributes(dmpi, mpi);
        dmpi->planes[0]=mpi->planes[0];
        dmpi->planes[1]=mpi->planes[1];
        dmpi->planes[2]=mpi->planes[2];
        dmpi->stride[0]=mpi->stride[0];
        dmpi->stride[1]=mpi->stride[1];
        dmpi->stride[2]=mpi->stride[2];
        dmpi->width=mpi->width;
        dmpi->height=mpi->height;
    }

    if(vf->priv->shot) {
        if (vf->priv->shot==1)
            vf->priv->shot=0;
        gen_fname(vf->priv);
        if (vf->priv->fname[0]) {
            if (!vf->priv->store_slices)
              scale_image(vf->priv, dmpi);
            write_png(vf->priv);
        }
        vf->priv->store_slices = 0;
    }

    return vf_next_put_image(vf, dmpi, pts);
}
Exemplo n.º 7
0
int
main(int argc, char **argv) 
{
  char image_data[3*16 * 3*16 * 3];
  int i,j,k,l,m;
  char r,g,b,t, or,og,ob;

  or=0x00; og=0xFF; ob=0x0;
  m=0;
  for (i=0; i<3; i++) {
    t=or; or=og; og=ob; ob=t;
    for (j=0; j<16; j++) {
      r=or; g=og; b=ob;
      for (k=0; k<3; k++) {
	for (l=0; l<16; l++) {
	  image_data[m++]=r;
	  image_data[m++]=g;
	  image_data[m++]=b;
	}
	t=r; r=g; g=b; b=t;
      }
    }
  }
  
  write_png("/tmp/pngtest.png", 3*16, 3*16, (void *) image_data) ;
  return 0;
}
Exemplo n.º 8
0
void write_image(char *file_name, int render_fmt, VInfo *ji, uint8_t *buf) {
  FILE *x;
  if ((x = open_outfile(file_name))) {
    switch (render_fmt) {
      case FMT_JPG:
	if (write_jpeg(ji, buf, JPEG_QUALITY, x))
	  dlog(LOG_ERR, "IMF: Could not write jpeg: %s\n", file_name);
	break;
      case FMT_PNG:
	if (write_png(ji, buf, x))
	  dlog(LOG_ERR, "IMF: Could not write png: %s\n", file_name);
	break;
      case FMT_PPM:
	if (write_ppm(ji, buf, x))
	  dlog(LOG_ERR, "IMF: Could not write ppm: %s\n", file_name);
	break;
      default:
	dlog(LOG_ERR, "IMF: Unknown outformat %d\n", render_fmt);
	break;
    }
    if (strcmp(file_name, "-")) fclose(x);
    dlog(LOG_INFO, "IMF: Outputfile %s closed\n", file_name);
  }
  else
    dlog(LOG_ERR, "IMF: Could not open outfile: %s\n", file_name);
  return;
}
Exemplo n.º 9
0
int main(int argc, char *argv[])
{
	clock_t start;
	LCUI_Graph slot, graph;
	/* 初始化数据结构 */
	Graph_Init( &graph );
	Graph_Init( &slot );
	
	if(argc == 2) {
		/* 载入图片文件 */
		if( Load_Image( argv[1], &graph ) != 0) {
			printf("can not load images!\n");
			return -1;
		}
		/* 开始计时 */
		start = clock(); 
		/* 默认使用高斯模糊算法,输入数据为graph, 数据输出至slot, sigma = 20 */
		Graph_Smooth( &graph, &slot, 20.0 );
		printf("smooth, use time: %ld us\n", clock()-start);
		start = clock();
		/* 将图像数据保存至文件 */
		write_png( "output.png", &slot );
		printf("write, use time: %ld us\n", clock()-start);
		/* 释放资源 */
		Graph_Free( &slot );
		Graph_Free( &graph );
	} else {
		printf( "usage:\n%s  imgfile\n", argv[0] );
	}
	return 0;
}
Exemplo n.º 10
0
void save(){
  unsigned char   **image;         // image[HEIGHT][WIDTH]の形式です

  int             i, j, pixeldata;
  XImage *ximage;
  
  image = (unsigned char**)malloc(height * sizeof(unsigned char*)); // 以下3行は2次元配列を確保します
  for (j = 0; j < height; j++)
    image[j] = (unsigned char*)malloc(width * sizeof(unsigned char) * 3);

  for (j = 0; j < height; j++) {
    ximage = XGetImage(dis,history_pix[(next+MAX_HISTORY-1)%MAX_HISTORY],0,j,width,1,AllPlanes,ZPixmap);
  
    for(i=0;i<width;i++){
      pixeldata = XGetPixel(ximage,i,0);
      image[j][3*i] = pixeldata>>16&0xff;
      image[j][3*i+1] = pixeldata>>8&0xff;
      image[j][3*i+2] = pixeldata&0xff;
    }
    //XPutImage(dis,canvas,hcopy_gc,ximage,0,j,0,j,width,1);
  }
  write_png("test2.png", image, width, height);                           // PNGファイルを作成します
  for (j = 0; j < height; j++) free(image[j]);            // 以下2行は2次元配列を解放します
  free(image);
  
}
Exemplo n.º 11
0
void write_screenshot(const Graphics::ScreendumpState &sd, const char* destFile)
{
	const std::string dir = "screenshots";
	FileSystem::userFiles.MakeDirectory(dir);
	const std::string fname = FileSystem::JoinPathBelow(dir, destFile);

	write_png(FileSystem::userFiles, fname, sd.pixels.get(), sd.width, sd.height, sd.stride, sd.bpp);

	Output("Screenshot %s saved\n", fname.c_str());
}
Exemplo n.º 12
0
SkData* Request::writeCanvasToPng(SkCanvas* canvas) {
    // capture pixels
    SkAutoTDelete<SkBitmap> bmp(getBitmapFromCanvas(canvas));
    SkASSERT(bmp);

    // write to png
    SkDynamicMemoryWStream buffer;
    write_png((const png_bytep) bmp->getPixels(), bmp->width(), bmp->height(), buffer);
    return buffer.copyToData();
}
int
main ()
{
    static const pixman_point_fixed_t inner = { 0x0000, 0x0000 };
    static const pixman_point_fixed_t outer = { 0x0000, 0x0000 };
    static const pixman_fixed_t r_inner = 0;
    static const pixman_fixed_t r_outer = 64 << 16;
    static const pixman_gradient_stop_t stops[] = {
	{ 0x00000, { 0x6666, 0x6666, 0x6666, 0xffff } },
	{ 0x10000, { 0x0000, 0x0000, 0x0000, 0xffff } }
    };
    static const pixman_transform_t transform = {
	{ { 0x0,        0x26ee, 0x0}, 
	  { 0xffffeeef, 0x0,    0x0}, 
	  { 0x0,        0x0,    0x10000}
	}
    };
    static const pixman_color_t z = { 0x0000, 0x0000, 0x0000, 0x0000 };
    pixman_image_t *dest, *radial, *zero;
    int i;
    double before, after;

    dest = pixman_image_create_bits (
	PIXMAN_x8r8g8b8, 640, 429, NULL, -1);
    zero = pixman_image_create_solid_fill (&z);
    radial = pixman_image_create_radial_gradient (
	&inner, &outer, r_inner, r_outer, stops, ARRAY_LENGTH (stops));
    pixman_image_set_transform (radial, &transform);
    pixman_image_set_repeat (radial, PIXMAN_REPEAT_PAD);

#define N_COMPOSITE	500

    before = gettime();
    for (i = 0; i < N_COMPOSITE; ++i)
    {
	before -= gettime();

	pixman_image_composite (
	    PIXMAN_OP_SRC, zero, NULL, dest,
	    0, 0, 0, 0, 0, 0, 640, 429);

	before += gettime();

	pixman_image_composite32 (
	    PIXMAN_OP_OVER, radial, NULL, dest,
	    - 150, -158, 0, 0, 0, 0, 640, 361);
    }

    after = gettime();

    write_png (dest, "radial.png");

    printf ("Average time to composite: %f\n", (after - before) / N_COMPOSITE);
    return 0;
}
Exemplo n.º 14
0
/* D. Hunt 9/9/09 at 8:54am */
int
write_png_mem(char **img_ptr, size_t *img_size, int width, int height, unsigned char *rgb)
{
    FILE *out;
    int success = 0;
    out = open_memstream(img_ptr, img_size);
    if (out == NULL) return (0);
    success = write_png(out, width, height, rgb, alpha);
    fclose(out);
    return(success);
}
Exemplo n.º 15
0
int main()
{
	int width = 2;
	int height = 2;
	char d[] = {
		0xff, 0xaa, 0x55, 0xff,
		0xff, 0x55, 0xaa, 0xff,
		0xff, 0xaa, 0x55, 0xff,
		0xff, 0x55, 0xaa, 0xff,
	};
	write_png("out.png",d, width, height);
	return 0;
}
Exemplo n.º 16
0
bool GenericImage::save(const char* filename)
{
    const char *ext = filename + strlen(filename) - 4;
    
    if (!strcmp(ext, ".png") || !strcmp(ext, ".PNG"))
        write_png(filename);
    else if (!strcmp(ext, ".jpg") || !strcmp(ext, ".JPG"))
        write_jpg(filename, 100);
//    else if (!strcmp(ext, ".raw") || !strcmp(ext, ".RAW"))
//        write_raw(filename);
    else return false;
	
    return true;
}
Exemplo n.º 17
0
    void image::write(std::string filename)
    {
        // switch on extension
        // that's the only way to find the format
        if (filename.find(".ppm") != std::string::npos)
            throw image_write_exception("image::write() Cannot Write .ppm files");
        else if (filename.find(".jpg") != std::string::npos || filename.find(".jpeg") != std::string::npos)
            write_jpeg(filename);
        else if (filename.find(".png") != std::string::npos)
            write_png(filename);
        else
            throw image_write_exception("image::write() Unrecognized Extention");

    }
Exemplo n.º 18
0
int
main (int argc, char *argv[])
{
	QFile      *bspfile;
	bsp_t      *bsp;
	image_t    *image;

	/* Enough args? */
	if (argc < 3) {
		show_help ();
		return 1;
	}

	/* Setup options */
	def_options (&options);
	get_options (&options, argc, argv);
	show_options (&options);

	bspfile = Qopen (options.bspf_name, "rbz");
	if (bspfile == NULL) {
		fprintf (stderr, "Error opening bsp file %s.\n", options.bspf_name);
		return 1;
	}
	bsp = LoadBSPFile (bspfile, Qfilesize (bspfile));
	Qclose (bspfile);

	image = render_map (bsp);
	BSP_Free (bsp);

	/* Write image */

	switch (options.outf_type) {
		case 0:
			write_pcx (image);
			break;
		case 1:
			write_png (image);
			break;
	}

	printf ("File written to %s.\n", options.outf_name);

	/* Close, done! */

	free (image->image);
	free (image);

	return 0;
}
Exemplo n.º 19
0
int main(int argc, char ** argv){
  int i,j;
  Image * a;
  Image * b;
  Image * res;
  Image * res_den;
  Image * p_res;
  real saturation = 250;
  if(argc < 4){
    printf("Usage: %s <saturation> <img1.h5> ... <imgN.h5>\n",argv[0]);
    return 0;
  }
  saturation = atof(argv[1]);
  for(j = 3;j<argc;j++){
    a = read_imagefile(argv[j-1]);  
    if(!res){
      res = create_empty_img(a);
      res_den = create_empty_img(a);
    }
    b = read_imagefile(argv[j]);
    p_res = create_empty_img(a);
    if(sp_cmatrix_size(a->image) != sp_cmatrix_size(b->image)){
      printf("Error: images should have the same dimensions!\n");
    return 1;
    }
    for(i = 0;i<sp_cmatrix_size(a->image);i++){
      if(b->image->data[i] && a->image->data[i] &&
	 creal(b->image->data[i]) < saturation && creal(a->image->data[i]) < saturation){
	p_res->image->data[i] = a->image->data[i]/b->image->data[i];
	res_den->image->data[i] += 1;
      }else{
	p_res->image->data[i] = 0;
      }
    }
    add_image(res,p_res);
    freeimg(p_res);
    freeimg(a);
    freeimg(b);
  }

  for(i = 0;i<sp_cmatrix_size(res->image);i++){
    if(res_den->image->data[i]){
      res->image->data[i] /= res_den->image->data[i];
    }
  }
  write_vtk(res,"analyze_image.vtk");
  write_png(res,"analyze_image.png",COLOR_JET);
  return 0;
}
Exemplo n.º 20
0
bool write_image(char *file_name, int width, int height, int nbytes, UCHAR *image,
				 double *geotiffInfo, DWORD jpegQuality, DWORD tiffCompression)
{
	const char *p = strrchr(file_name, '.');
	if (!p) return false;

	if (!_stricmp(p, ".jpg"))
		return write_jpeg(file_name, width, height, nbytes, image, jpegQuality);

	if (!_stricmp(p, ".tif"))
		return write_tiff(file_name, width, height, nbytes, image, geotiffInfo, jpegQuality, tiffCompression);

	if (!_stricmp(p, ".png"))
		return write_png(file_name, width, height, nbytes, image);

	return false;
}
Exemplo n.º 21
0
int IMG_SavePNG(const char* filename, SDL_Surface* surf) {
	unsigned char** ss_rows = NULL;
	SDL_Surface* ss_surface = NULL;
	int i = 0;

	dbgout("Writing..\n");
	int result = 0;
	if (!surf) {
		dbgout("Invalid SDL_Surface\n");
		result = -1;
	} else {
		dbgout("Performing Lock\n");

		/*Create a surface formatted just for PNG saving since it must be 24bit*/
	    ss_surface =
			SDL_CreateRGBSurface(SDL_SWSURFACE, surf->w, surf->h,
								24, RMASK, GMASK, BMASK, AMASK);
		if (!ss_surface) {
			dbgout("Failed to allocate PNG surface\n");
			return -1;
		}

		dbgout("Making Rows\n");
	    ss_rows = (unsigned char**)malloc(sizeof(unsigned char*) * surf->h);

		dbgout("Blitting\n");
	    SDL_BlitSurface(surf, NULL, ss_surface, NULL); /* Render the pic onto the formatted surface */

		dbgout("Lock and copy\n");
		if (SDL_MUSTLOCK(surf))
			SDL_LockSurface(surf);
	    for (i = 0; i < surf->h; i++) {
	      ss_rows[i] = ((unsigned char*)ss_surface->pixels) + i * ss_surface->pitch;
	    }
		if (SDL_MUSTLOCK(surf))
			SDL_UnlockSurface(surf);

		dbgout("Writing\n");
	    write_png(filename, ss_rows, surf->w, surf->h, PNG_COLOR_TYPE_RGB, 8);
		dbgout("Freeing\n");
		free(ss_rows);
		SDL_FreeSurface(ss_surface);
	}
	dbgout("Done\n");
	return result;
}
Exemplo n.º 22
0
int main(int argc, char** argv) {
    if(argc < 3) {
        fprintf(stderr, "Usage: %s <source out> <header out> <png in>...\n",
                        argv[0]);
        return 1;
    }

    FILE *source = fopen(argv[1], "wt");
    if(!source)
        die("source fopen failed");

    FILE *header = fopen(argv[2], "wt");
    if(!header)
        die("header fopen failed");

    fprintf(source, "/**** This is a generated file - do not edit ****/\n\n");
    fprintf(header, "/**** This is a generated file - do not edit ****/\n\n");

    for(int i = 3; i < argc; i++) {
        const char *filename = argv[i];
        const char *basename = strrchr(filename, '/'); /* cmake uses / even on Windows */
        if(basename == NULL) {
            basename = filename;
        } else {
            basename++; // skip separator
        }

        char *stemname = (char*) calloc(strlen(basename), 1);
        strncpy(stemname, basename, strchr(basename, '.') - basename);
        for(size_t j = 0; j < strlen(stemname); j++) {
            if(!isalnum(stemname[j]))
                stemname[j] = '_';
        }

        fprintf(header, "extern unsigned char Icon_%s[24*24*3];\n", stemname);

        fprintf(source, "unsigned char Icon_%s[24*24*3] = {\n", stemname);
        write_png(source, filename);
        fprintf(source, "};\n\n");

        free(stemname);
    }

    fclose(source);
    fclose(header);
}
Exemplo n.º 23
0
bool write_png(const boost::multi_array<double,2>& value,
               const char* filename)
{

    int	n0=value.shape()[0];
    int	n1=value.shape()[1];
    boost::multi_array<png::rgb,2>	pixels(boost::extents[n0][n1]);

    double	x;
    for(int i=0; i<n0; i++) {
        for(int j=0; j<n1; j++) {
            x=value[i][j];
            if(x<0.0) x=0.0;
            if(x>1.0) x=1.0;
            pixels[i][j]=wavelength2rgb(420.0+200.0*x);
        }
    }
    return write_png(pixels,filename);
}
Exemplo n.º 24
0
/**
 * Save image
 * Parameters:
 *      path:   output path 
 *      mem:    bitmap in memory
 * Return:
 *           0  OK
 *          -1  ERROR
 */
int saveImage (const char *path, const Bitmap_t *mem) 
{
    VALIDATE_NOT_NULL2 (path, mem);
    const char const *postfix = getFilePostfix (path);
    if (NULL == postfix) {
        LogE ("Failed getFilePostfix in saveImage\n");
        return -1;
    }

    if (strcasecmp (postfix, "jpg") == 0) {
        return write_jpeg (path, mem);
    }
    else if (strcasecmp (postfix, "png") == 0) {
        return write_png (path, mem);
    }
    else {
        LogE ("Invalid postfix name (%s) in saveImage\n", postfix);
        return -1;
    }
}
Exemplo n.º 25
0
void Screendump(const char* destFile, const int width, const int height)
{
	const std::string dir = "screenshots";
	FileSystem::userFiles.MakeDirectory(dir);
	const std::string fname = FileSystem::JoinPathBelow(dir, destFile);

	// pad rows to 4 bytes, which is the default row alignment for OpenGL
	const int stride = (3*width + 3) & ~3;

	std::vector<Uint8> pixel_data(stride * height);
	glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
	glPixelStorei(GL_PACK_ALIGNMENT, 4); // never trust defaults
	glReadBuffer(GL_FRONT);
	glReadPixels(0, 0, width, height, GL_RGB, GL_UNSIGNED_BYTE, &pixel_data[0]);
	glFinish();

	write_png(FileSystem::userFiles, fname, &pixel_data[0], width, height, stride, 3);

	Output("Screenshot %s saved\n", fname.c_str());
}
Exemplo n.º 26
0
int main(int argc, char **argv) {
	FILE *fp = stdout;
	const char *file_name = NULL;
	unsigned int colors[5];
	unsigned int filters = PNG_ALL_FILTERS;
	int color_type,bit_depth;
	png_fixed_point gamma;
 
	memset(colors, 0, sizeof colors);

	gamma = PNG_DEFAULT_sRGB;
	color_type = PNG_COLOR_TYPE_RGB_ALPHA;
	bit_depth=8;
	//filters &= ~(PNG_FILTER_NONE | PNG_FILTER_AVG);
	filters = PNG_FILTER_NONE;
//	fp = fopen("lixo.png", "wb");
	int ret = write_png(&file_name, fp, color_type, bit_depth, gamma, filters, colors);
	if (ret != 0 && file_name != NULL) remove(file_name);
	return ret;
}
Exemplo n.º 27
0
void run_callb(GtkWidget *wdg, gpointer render_struct_ptr) {
//	Render a povray image, display only
//	First we save the image under HF_OUTPUT_FOR_RENDERING
//	(usually test.png) in the current directory
	gchar *dir;
	gfloat ar;
	render_struct *rs = (render_struct *) render_struct_ptr;
	if (wdg)
		if (GTK_IS_TOGGLE_BUTTON(wdg))
			if (!gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(wdg)))
				return;
	if (!rs)
		return;
	dir = (gchar *) get_current_dir_name();
	chdir(TMP_DIR);
	// If the current height field has not been changed, we render the source file
//	printf("if_creation: %d; if_modified: %d; (x,y): (%d,%d)\n",*rs->if_creation, *rs->if_modified, rs->max_x, rs->max_y);
	if (*rs->if_creation || *rs->if_modified)  {
//		printf("\n*************\n\nSAVING in %s/%s\n\n*************\n",TMP_DIR, HF_OUTPUT_FOR_RENDERING);
		write_png (HF_OUTPUT_FOR_RENDERING, 16, (gchar *) rs->grid, rs->max_x, rs->max_y);
	}
		
	// Patch 2005-05 - Deduce aspect ratio from image size,
	// backup the original (which is the preview W/H ratio), maybe for the future...
/*
printf("RS: %d\n",rs);
printf("RS->gl_preview: %d\n",rs->gl_preview);
printf("RS->gl_preview->cameras: %d\n",rs->gl_preview->cameras);
printf("RS->gl_preview->current_camera_id: %d\n",rs->gl_preview->current_camera_id);
*/
	ar = rs->gl_preview->cameras[rs->gl_preview->current_camera_id]->aspect_ratio;
	rs->gl_preview->cameras[rs->gl_preview->current_camera_id]->aspect_ratio = ((gfloat) RENDER_WIDTH) / (gfloat) RENDER_HEIGHT;
	
	gl_save_camera_inc (rs->gl_preview->cameras[rs->gl_preview->current_camera_id]);
	gl_save_water_inc (rs->gl_preview);
	rs->gl_preview->cameras[rs->gl_preview->current_camera_id]->aspect_ratio = ar;
	render_pov(rs);
	chdir(dir);
	free(dir);
}
Exemplo n.º 28
0
void 
VCDSubDumpPNG( uint8_t *p_image, decoder_t *p_dec,
	       uint32_t i_height, uint32_t i_width, const char *filename,
	       png_text *text_ptr, int i_text_count )
{
  decoder_sys_t *p_sys = p_dec->p_sys;
  uint8_t *p = p_image;
  uint8_t *image_data = malloc(RGB_SIZE * i_height * i_width );
  uint8_t *q = image_data;
  unsigned int i_row;    /* scanline row number */
  unsigned int i_column; /* scanline column number */
  uint8_t rgb_palette[PALETTE_SIZE * RGB_SIZE];
  int i;

  dbg_print( (DECODE_DBG_CALL), "%s", filename);
  
  if (NULL == image_data) return;

  /* Convert palette YUV into RGB. */
  for (i=0; i<PALETTE_SIZE; i++) {
    ogt_yuvt_t *p_yuv     = &(p_sys->p_palette[i]);
    uint8_t   *p_rgb_out  = &(rgb_palette[i*RGB_SIZE]);
    yuv2rgb( p_yuv, p_rgb_out );
  }
  
  /* Convert palette entries into linear RGB array. */
  for ( i_row=0; i_row < i_height; i_row ++ ) {
    for ( i_column=0; i_column<i_width; i_column++ ) {
      uint8_t *p_rgb = &rgb_palette[ ((*p)&PALETTE_SIZE_MASK)*RGB_SIZE ];
      *q++ = p_rgb[0];
      *q++ = p_rgb[1];
      *q++ = p_rgb[2];
      p++;
    }
  }
  
  write_png( filename, i_height, i_width, image_data, text_ptr, i_text_count );
  free(image_data);
}
Exemplo n.º 29
0
void save_png(){
  Window savemap;
  unsigned char   **image;         // image[HEIGHT][WIDTH]の形式です
  int             i, j, pixeldata;
  XImage *ximage;
  
  savemap = XCreateSimpleWindow( dis, canvas,
				 0, 0,
				 CANV_WIDTH, CANV_HEIGHT,
				 0, 0, 0 );
  XSetWindowBackgroundPixmap( dis, savemap, None );//背景を透明に
  XMapWindow(dis,savemap);

  image = (unsigned char**)malloc(CANV_HEIGHT * sizeof(unsigned char*)); // 以下3行は2次元配列を確保します
  for (j = 0; j < CANV_HEIGHT; j++)
    image[j] = (unsigned char*)malloc(CANV_WIDTH * sizeof(unsigned char) * 3);

  for (j = 0; j < CANV_HEIGHT; j++) {
    ximage = XGetImage(dis,savemap,0,j,CANV_WIDTH,1,AllPlanes,ZPixmap);
  
    for(i=0;i<CANV_WIDTH;i++){
      pixeldata = XGetPixel(ximage,i,0);
      image[j][3*i] = pixeldata>>16&0xff;
      image[j][3*i+1] = pixeldata>>8&0xff;
      image[j][3*i+2] = pixeldata&0xff;
    }
    //XPutImage(dis,canvas,hcopy_gc,ximage,0,j,0,j,CANV_WIDTH,1);
  }
  write_png("test2.png", image, CANV_WIDTH, CANV_HEIGHT);            // PNGファイルを作成します
  for (j = 0; j < CANV_HEIGHT; j++) free(image[j]);            // 以下2行は2次元配列を解放します
  free(image);

  XUnmapWindow(dis,savemap);

  XDestroyWindow(dis,savemap);
  
}
Exemplo n.º 30
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;

}