Beispiel #1
0
int magickChopImage(const char *imageFile, const char *outputImage, int width, int height, int xPos, int yPos){
    MagickBooleanType status;

    MagickWand *magick_wand;

    /*
      Read an image.
    */
    MagickWandGenesis();
    magick_wand=NewMagickWand();  
    status=MagickReadImage(magick_wand, (char *)imageFile);
    if (status == MagickFalse){
      ThrowWandException(magick_wand);
    }
    /*
      Turn the images into a thumbnail sequence.
    */
    MagickResetIterator(magick_wand);
    while (MagickNextImage(magick_wand) != MagickFalse)
      MagickChopImage(magick_wand, width, height, xPos, yPos);
    /*
      Write the image then destroy it.
    */
    status=MagickWriteImages(magick_wand, (char *)outputImage, MagickTrue);
    if (status == MagickFalse)
      ThrowWandException(magick_wand);
    magick_wand=DestroyMagickWand(magick_wand);
    MagickWandTerminus();
    return status;
}
Beispiel #2
0
int magickCompressImage(const char *imageFile, const char *outputImage, const char *format, int compressionType, double compressionRate){
    MagickBooleanType status;

    MagickWand *magick_wand;

    /*
      Read an image.
    */
 //   printf("compressionRate: %d", compressionRate);
    MagickWandGenesis();
    magick_wand=NewMagickWand();  
    status=MagickReadImage(magick_wand, (char *)imageFile);
    if (status == MagickFalse){
      ThrowWandException(magick_wand);
    }
    /*
      Turn the images into a thumbnail sequence.
    */
//    MagickResetIterator(magick_wand);
//    while (MagickNextImage(magick_wand) != MagickFalse){
        MagickSetFormat(magick_wand, (char *)format);
        MagickSetImageCompression(magick_wand, compressionType);
        MagickSetImageCompressionQuality(magick_wand, compressionRate);
//    }

    /*
      Write the image then destroy it.
    */
    status=MagickWriteImages(magick_wand, (char *)outputImage, MagickTrue);
    if (status == MagickFalse)
      ThrowWandException(magick_wand);
    magick_wand=DestroyMagickWand(magick_wand);
    MagickWandTerminus();
    return status;
}
Beispiel #3
0
int magickResizeImage(const char *imageFile, const char *outputImage, int columns, int rows, int magickFilter, double blur){
    MagickBooleanType status;

    MagickWand *magick_wand;

    /*
      Read an image.
    */
    MagickWandGenesis();
    magick_wand=NewMagickWand();  
    status=MagickReadImage(magick_wand, (char *)imageFile);
    if (status == MagickFalse){
      ThrowWandException(magick_wand);
    }
    /*
      Turn the images into a thumbnail sequence.
    */
    MagickResetIterator(magick_wand);
    while (MagickNextImage(magick_wand) != MagickFalse)
      MagickResizeImage(magick_wand, columns, rows, LanczosFilter, blur);
    /*
      Write the image then destroy it.
    */
    status=MagickWriteImages(magick_wand, (char *)outputImage, MagickTrue);
    if (status == MagickFalse)
      ThrowWandException(magick_wand);
    magick_wand=DestroyMagickWand(magick_wand);
    MagickWandTerminus();
    return status;
    
}
Beispiel #4
0
int magickRotateImage(const char *imageFile, const char *outputImage, double degree){
    MagickBooleanType status;
    MagickWand *magick_wand;

    PixelWand * bg = malloc(sizeof(PixelWand *));
    /*
      Read an image.
    */
    MagickWandGenesis();
    magick_wand=NewMagickWand();  
    status=MagickReadImage(magick_wand, (char *)imageFile);
    if (status == MagickFalse){
      ThrowWandException(magick_wand);
    }
    /*
      Turn the images into a thumbnail sequence.
    */
    MagickResetIterator(magick_wand);
    while (MagickNextImage(magick_wand) != MagickFalse)
      MagickRotateImage(magick_wand, bg, degree);
//    MagickSetImageCompression(magick_wand, MW_JPEGCompression);
//    MagickUnsharpMaskImage( magick_wand, 4.5, 4.0, 4.5, 0.02 );
    /*
      Write the image then destroy it.
    */
    status=MagickWriteImages(magick_wand, (char *)outputImage, MagickTrue);
    if (status == MagickFalse)
      ThrowWandException(magick_wand);
    magick_wand=DestroyMagickWand(magick_wand);
    MagickWandTerminus();
    return status;
}
Beispiel #5
0
int barcode_to_png (char *image_name) {
  MagickWand *magick_wand;
  MagickBooleanType status;

  int width, height, pad, half_pad;

  /* read a barcode image */
  MagickWandGenesis();
  magick_wand = NewMagickWand();
  MagickSetResolution(magick_wand, 300, 300);
  status = MagickReadImage(magick_wand, image_name);
  if (status == MagickFalse) ThrowWandException(magick_wand, 1);

  /* trim the image, resample it, and pad it by [10% of the long side] per side */
  MagickTrimImage(magick_wand, 10);
  width = MagickGetImageWidth(magick_wand);
  height = MagickGetImageHeight(magick_wand);
  pad = determine_padding(width, height);
  half_pad = round(pad/2);
  MagickExtentImage(magick_wand, width+pad, height+pad, -half_pad, -half_pad);
  
  /* write image (a PNG version and a formatted PS version) */
  status=MagickWriteImage(magick_wand, chop_path(image_name, ".png"));
  if (status == MagickFalse) ThrowWandException(magick_wand, 2);
  status=MagickWriteImage(magick_wand, chop_path(image_name, ".ps"));
  if (status == MagickFalse) ThrowWandException(magick_wand, 2);

  /* clean up */
  magick_wand=DestroyMagickWand(magick_wand);
  MagickWandTerminus();

  return 0;
}
Beispiel #6
0
int magickModulateImage(const char *imageFile, const char *outputImage, double brightness, double saturation, double hue){
    MagickBooleanType status;

    MagickWand *magick_wand;

    /*
      Read an image.
    */
    MagickWandGenesis();
    magick_wand=NewMagickWand();  
    status=MagickReadImage(magick_wand, (char *)imageFile);
    if (status == MagickFalse){
      ThrowWandException(magick_wand);
    }
    /*
      Turn the images into a thumbnail sequence.
    */
    MagickResetIterator(magick_wand);
    while (MagickNextImage(magick_wand) != MagickFalse)
      MagickModulateImage(magick_wand, brightness, saturation, hue);
    /*
      Write the image then destroy it.
    */
    status=MagickWriteImages(magick_wand, (char *)outputImage, MagickTrue);
    if (status == MagickFalse)
      ThrowWandException(magick_wand);
    magick_wand=DestroyMagickWand(magick_wand);
    MagickWandTerminus();
    return status;
}
Beispiel #7
0
int magickUnsharpMaskImage(const char *imageFile, const char *outputImage, double radius, double sigma, double amount, double threshold){
    MagickBooleanType status;

    MagickWand *magick_wand;

    /*
      Read an image.
    */
    MagickWandGenesis();
    magick_wand=NewMagickWand();  
    status=MagickReadImage(magick_wand, (char *)imageFile);
    if (status == MagickFalse){
      ThrowWandException(magick_wand);
    }
    /*
      Turn the images into a thumbnail sequence.
    */
//    MagickResetIterator(magick_wand);
//    while (MagickNextImage(magick_wand) != MagickFalse)
      MagickUnsharpMaskImage(magick_wand, radius, sigma, amount, threshold);
    /*
      Write the image then destroy it.
    */
    status=MagickWriteImages(magick_wand, (char *)outputImage, MagickTrue);
    if (status == MagickFalse)
      ThrowWandException(magick_wand);
    magick_wand=DestroyMagickWand(magick_wand);
    MagickWandTerminus();
    return status;
}
Beispiel #8
0
int raster(MagickWand *image_wand, char **outBuffer)
{

	char *localPointer;
	PixelIterator *iterator;
	PixelWand **pixels;
	register long x;
	long y;
	unsigned long columns, rows;
	int bufcnt = 0;

	/*
	 * allocate buffer
	 */

	columns = MagickGetImageHeight(image_wand);
	rows = MagickGetImageWidth(image_wand);

	fprintf(stderr,"Image size : %ldx%ld\n", columns, rows);
	int outSize = 9 * rows * columns * sizeof(char);
	localPointer = (char*) malloc(outSize);
	if (localPointer == NULL)
	{
		perror("malloc");
		return 0;
	}

	/*
	 * convert wand into a buffer
	 */

	iterator = NewPixelIterator(image_wand);
	if (iterator == (PixelIterator *) NULL)
		ThrowWandException(image_wand);
	for (y = 0; y < (long) columns; y++)
	{
		pixels = PixelGetNextIteratorRow(iterator, &rows);
		if (pixels == (PixelWand **) NULL)
			break;
		for (x = 0; x < (long) rows; x++)
			bufcnt += sprintf(localPointer + bufcnt, "defb &%2.2X\n",
					cpc2raster(pixel2cpc(pixels[x])));
	}

	if (y < (long) columns)
		ThrowWandException(image_wand);
	iterator = DestroyPixelIterator(iterator);
	image_wand = DestroyMagickWand(image_wand);
	MagickWandTerminus();

	*outBuffer = localPointer;
	return bufcnt;
}
Beispiel #9
0
int main(int argc, char **argv){
    if (argc != 4){
        (void) fprintf(stdout,"Usage: %s palette input-file output-file\n",argv[0]);
        exit(0);
    }
    read_palette(argv[1]);
    print_palette();
    
    char *description;
    ExceptionType severity;


    #define ThrowWandException(wand) \
    { \
        description=MagickGetException(wand,&severity); \
        (void) fprintf(stderr,"%s %s %lu %s\n",GetMagickModule(),description); \
        description=(char *) MagickRelinquishMemory(description); \
        exit(-1); \
    }

    MagickBooleanType status;
    MagickPixelPacket pixel;
    MagickWand *wand;
    WandView *view;
    /*
       Read an image.
       */
    MagickWandGenesis();
    wand = NewMagickWand();
    status = MagickReadImage(wand, argv[2]);
    if (status == MagickFalse) ThrowWandException(wand);

    /*
       Sigmoidal non-linearity contrast control.
       */
    view = NewWandView(wand);
    if (view == (WandView *) NULL) ThrowWandException(wand);
    status = UpdateWandViewIterator(view, recolor, (void *)NULL);
    if (status == MagickFalse) ThrowWandException(wand);
    view = DestroyWandView(view);

    /*
       Write the image then destroy it.
       */
    status = MagickWriteImages(wand, argv[3], MagickTrue);
    if (status == MagickFalse) ThrowWandException(wand);
    wand = DestroyMagickWand(wand);
    MagickWandTerminus();

    return 0;
}
Beispiel #10
0
unsigned char *get_transition_image_blob(char *file_buf, int buf_size,
		size_t * thumbnail_size, img_transition_info *image_transition_info) {

	unsigned char *image_data = NULL;

	if (file_buf == NULL)
		return NULL;
	if (image_transition_info == NULL)
		return NULL;
	if ((0 == image_transition_info->is_rotate)
			&& ('\0' == image_transition_info->transition_str[0])
			&& (0 == image_transition_info->is_quality))
		return NULL;
	MagickBooleanType status;
	MagickWand *magick_wand = NULL;
	magick_wand = NewMagickWand();
	status = MagickReadImageBlob(magick_wand, file_buf, buf_size);
	if (status == MagickFalse) {
		ThrowWandException(magick_wand);
		return NULL;
	}
	image_data = covert_image(magick_wand, image_transition_info,
			thumbnail_size);
	magick_wand = DestroyMagickWand(magick_wand);
	return image_data;

}
Beispiel #11
0
ARUint8* loadImage(char* filename, int* xsize, int* ysize)
{
	ARUint8 *dptr;
	
	Image *image;
	MagickWand* magick_wand;

	magick_wand=NewMagickWand(); 
    if( magick_wand == NULL) {
        fprintf(stderr, "bad magickwand\n");
    }

	MagickBooleanType status=MagickReadImage(magick_wand,filename);
	if (status == MagickFalse) {
		//fprintf(stderr, "%s can't be read\n", filename);
		//exit(1);
        //return; //(1);
		ThrowWandException(magick_wand);
	}

	image = GetImageFromMagickWand(magick_wand);

	//ContrastImage(image,MagickTrue); 
	//EnhanceImage(image,&image->exception); 

	int index;

	*xsize = image->columns;
	*ysize = image->rows;
		
	dptr = malloc(sizeof(ARUint8) * 3 * image->rows * *xsize);
	int y;
	index = 0;
	for (y=0; y < (long) image->rows; y++)
	{
		const PixelPacket *p = AcquireImagePixels(image,0,y,*xsize,1,&image->exception);
		if (p == (const PixelPacket *) NULL)
			break;
		int x;
		for (x=0; x < (long) *xsize; x++)
		{
			/// convert to ARUint8 dptr
			/// probably a faster way to give the data straight over
			/// in BGR format
			dptr[index*3+2]   = p->red/256;
			dptr[index*3+1] = p->green/256;
			dptr[index*3] = p->blue/256;
			
			//fprintf(stderr,"%d, %d, %d\t%d\t%d\n", x, y, p->red/256, p->green/256, p->blue/256);
			p++;
			index++;
		}
	}

    DestroyMagickWand(magick_wand);

	return dptr;
}
int main(int argc,char **argv) {
    
    MagickBooleanType status;
    PixelWand *pixelWand;

    MagickWand *magick_wand_a;
    MagickWand *magick_wand_b;
    //MagickWand *magick_wand_c;

    MagickWandGenesis();

    magick_wand_a = NewMagickWand();
    status = MagickReadImage(magick_wand_a, "./displaceCompositeA.png");
    if (status == MagickFalse) {
        ThrowWandException(magick_wand_a);
    }
    
    magick_wand_b = NewMagickWand();
    status = MagickReadImage(magick_wand_b, "./displaceMask.png");
    if (status == MagickFalse) {
        ThrowWandException(magick_wand_b);
    }
    
    MagickSetImageVirtualPixelMethod(magick_wand_a, TransparentVirtualPixelMethod);

    pixelWand = makePixelWand("none");
    status = MagickSetImageBackgroundColor(magick_wand_a, pixelWand);
    
    MagickSetOption(magick_wand_a, "compose:args", "300x53.033");
    status = MagickCompositeImage(magick_wand_a, magick_wand_b, DisplaceCompositeOp, 0, 0);
    if (status == MagickFalse) {
        printf("Failed to composite image b");
        exit(-1); 
    }
      
    status = MagickWriteImages(magick_wand_a, "displaceOutputMerged.png", MagickTrue);

    MagickWandTerminus();
    
    printf("Finished - please compare displaceOutputMerged.png with the result of:\n\n");

    printf("convert displaceCompositeA.png displaceMask.png -virtual-pixel transparent -channel rgba -alpha on -background transparent -define compose:args=300x53.033 -compose displace -composite displaceMerged.png");
    
    return(0);
}
G_MODULE_EXPORT void cb_image_save_ok_clicked(GtkButton *button)
{
  char *filename;
  filename = gtk_file_chooser_get_filename (GTK_FILE_CHOOSER (camera_params.objects->imagesavedialog));
  g_print("Saving to Filename %s\n",filename);
  
  if(camera_params.wand_data.saving_wand)
  {
    MagickBooleanType status;
    status=MagickSetImageFormat(camera_params.wand_data.saving_wand,"PNG");
    if (status == MagickFalse)
      ThrowWandException(camera_params.wand_data.saving_wand);
    status=MagickWriteImage(camera_params.wand_data.saving_wand,filename);
    if (status == MagickFalse)
      ThrowWandException(camera_params.wand_data.saving_wand);
    DestroyMagickWand(camera_params.wand_data.saving_wand);
  }
  g_free (filename);


  camera_params.wand_data.saving_wand=NULL;
  gtk_widget_hide( camera_params.objects->imagesavedialog );
}
Beispiel #14
0
int thumbnail (char *image_name, char *thumbnail_name, int thumb_width, int thumb_height){

  MagickWand *magick_wand;
  MagickBooleanType status;

  /* Read an image. */
  MagickWandGenesis();
  magick_wand=NewMagickWand();
  status=MagickReadImage(magick_wand, image_name);
  if (status == MagickFalse) ThrowWandException(magick_wand, 1);
  
  /* Turn the images into a thumbnail sequence. */
  MagickResetIterator(magick_wand);
  while (MagickNextImage(magick_wand) != MagickFalse)
    MagickResizeImage(magick_wand,thumb_width,thumb_height,LanczosFilter,1.0);

  /* Write the image then destroy it. */
  status=MagickWriteImages(magick_wand, thumbnail_name, MagickTrue);
  if (status == MagickFalse) ThrowWandException(magick_wand, 2);
  magick_wand=DestroyMagickWand(magick_wand);
  MagickWandTerminus();
  
  return 0;
}
Beispiel #15
0
int main(int argc,char **argv)
{
  char
    filename[MaxTextExtent];

  MagickBooleanType
    status;

  MagickWand
    *canvas;

  if (argc != 2)
    {
      (void) printf ("Usage: %s filename\n",argv[0]);
      exit(1);
    }
  (void) CopyMagickString(filename,argv[1],MaxTextExtent);
  /*
    Create canvas image.
  */
  MagickWandGenesis();
  canvas=NewMagickWand();
  status=MagickSetSize(canvas,596,842);
  if (status == MagickFalse)
    ThrowWandException(canvas);
  status=MagickReadImage(canvas,"xc:white");
  if (status == MagickFalse)
    ThrowWandException(canvas);
  /*
    Scribble on image.
  */
  status=ScribbleImage(canvas);
  if (status == MagickFalse)
    ThrowWandException(canvas);
  /*
    Set pixel depth to 8.
  */
  status=MagickSetImageDepth(canvas,8);
  if (status == MagickFalse)
    ThrowWandException(canvas);
  /*
    Set output as RLE compressed.
  */
  status=MagickSetImageCompression(canvas,RLECompression);
  if (status == MagickFalse)
    ThrowWandException(canvas);
  /*
    Save image to file.
  */
  status=MagickWriteImage(canvas,filename);
  if (status == MagickFalse)
    ThrowWandException(canvas);
  canvas=DestroyMagickWand(canvas);
  MagickWandTerminus();
  return(0);
}
Beispiel #16
0
  char *get_thumbnail(char *full_filename, char *thumbnail_str, size_t *thumbnail_size)
 {
	
	char image_data = NULL;
	if(full_filename == NULL || thumbnail_str == NULL)
		return NULL;
	MagickBooleanType  status;
   	MagickWand  *magick_wand, *tmp_magick_wand;
	magick_wand=NewMagickWand();
	status=MagickReadImage(magick_wand, full_filename);
	if (status == MagickFalse)
  	  ThrowWandException(magick_wand);
	size_t height = MagickGetImageHeight(magick_wand);
	size_t width = MagickGetImageWidth(magick_wand);
	ssize_t i, j;
	ParseMetaGeometry(thumbnail_str, &i, &j, &width, &height);
	if(width <= 0 || height <= 0)
	{
		logError("%s%s:Geometry  %s error\n", __FILE__, __func__, thumbnail_str);
	}
	else
	{
		/*
		if(is_gif(full_filename))
		{
			  tmp_magick_wand = magick_wand;
			  magick_wand = MagickCoalesceImages(tmp_magick_wand);
			  tmp_magick_wand =   DestroyMagickWand(tmp_magick_wand);
		}
		*/	
		 MagickResetIterator(magick_wand);
   		 while (MagickNextImage(magick_wand) != MagickFalse)
     		 {
     		 	MagickThumbnailImage(magick_wand,height,width);
   		 }
		image_data =  MagickGetImagesBlob(magick_wand, thumbnail_size);
	}
	
	magick_wand=DestroyMagickWand(magick_wand);
	return image_data;
}
Beispiel #17
0
  int main(int argc,char **argv)
  {
  #define ThrowWandException(wand) \
  { \
    char \
      *description; \
   \
    ExceptionType \
      severity; \
   \
    description=MagickGetException(wand,&severity); \
    (void) fprintf(stderr,"%s %s %ld %s\n",GetMagickModule(),description); \
    description=(char *) MagickRelinquishMemory(description); \
    exit(-1); \
  }
  
    MagickBooleanType
      status;
  
    MagickWand
      *magick_wand;
    MagickWand
      *tmp_magick_wand;
  
    /*
      Read an image.
    */
    size_t len;
    char *data;
		data = get_thumbnail(argv[1], argv[2], &len);
		MagickReadImageBlob(magick_wand, data, len);  
    status=MagickWriteImages(magick_wand,argv[3],MagickTrue);
    if (status == MagickFalse)
      ThrowWandException(magick_wand);
    magick_wand=DestroyMagickWand(magick_wand);
    MagickWandTerminus();
    return(0);
  }
Beispiel #18
0
/**
 * @brief get_img The function of getting a image buffer and it's length.
 *
 * @param req The zimg_req_t from zhttp and it has the params of a request.
 * @param buff_ptr This function return image buffer in it.
 * @param img_size Get_img will change this number to return the size of image buffer.
 *
 * @return 1 for success and -1 for fail.
 */
int get_img(zimg_req_t *req, evhtp_request_t *request)
{
    int result = -1;
    char cache_key[CACHE_KEY_SIZE];
    char *img_format = NULL;
    int fd = -1;
    struct stat f_stat;
    char *buff_ptr;
    size_t img_size;

    MagickBooleanType status;
    MagickWand *magick_wand = NULL;

    bool got_rsp = true;
    bool got_color = false;

    LOG_PRINT(LOG_DEBUG, "get_img() start processing zimg request...");

    // to gen cache_key like this: 926ee2f570dc50b2575e35a6712b08ce:0:0:1:0
    gen_key(cache_key, req->md5, 4, req->width, req->height, req->proportion, req->gray);
    if(find_cache_bin(req->thr_arg, cache_key, &buff_ptr, &img_size) == 1)
    {
        LOG_PRINT(LOG_DEBUG, "Hit Cache[Key: %s].", cache_key);
        goto done;
    }
    LOG_PRINT(LOG_DEBUG, "Start to Find the Image...");

    char whole_path[512];
    int lvl1 = str_hash(req->md5);
    int lvl2 = str_hash(req->md5 + 3);
    snprintf(whole_path, 512, "%s/%d/%d/%s", settings.img_path, lvl1, lvl2, req->md5);
    LOG_PRINT(LOG_DEBUG, "docroot: %s", settings.img_path);
    LOG_PRINT(LOG_DEBUG, "req->md5: %s", req->md5);
    LOG_PRINT(LOG_DEBUG, "whole_path: %s", whole_path);

    char name[128];
    if(req->proportion && req->gray)
        snprintf(name, 128, "%d*%dpg", req->width, req->height);
    else if(req->proportion && !req->gray)
        snprintf(name, 128, "%d*%dp", req->width, req->height);
    else if(!req->proportion && req->gray)
        snprintf(name, 128, "%d*%dg", req->width, req->height);
    else
        snprintf(name, 128, "%d*%d", req->width, req->height);

    char color_name[128];
    if(req->proportion)
        snprintf(color_name, 128, "%d*%dp", req->width, req->height);
    else
        snprintf(color_name, 128, "%d*%d", req->width, req->height);

    char orig_path[512];
    snprintf(orig_path, strlen(whole_path) + 6, "%s/0*0", whole_path);
    LOG_PRINT(LOG_DEBUG, "0rig File Path: %s", orig_path);

    char rsp_path[512];
    if(req->width == 0 && req->height == 0 && req->proportion == 0 && req->gray == 0)
    {
        LOG_PRINT(LOG_DEBUG, "Return original image.");
        strncpy(rsp_path, orig_path, 512);
    }
    else
    {
        snprintf(rsp_path, 512, "%s/%s", whole_path, name);
    }
    LOG_PRINT(LOG_DEBUG, "Got the rsp_path: %s", rsp_path);

    char color_path[512];
    snprintf(color_path, 512, "%s/%s", whole_path, color_name);


    //status=MagickReadImage(magick_wand, rsp_path);
    if((fd = open(rsp_path, O_RDONLY)) == -1)
    {
        magick_wand = NewMagickWand();
        got_rsp = false;

        if(req->gray == 1)
        {
            gen_key(cache_key, req->md5, 3, req->width, req->height, req->proportion);
            if(find_cache_bin(req->thr_arg, cache_key, &buff_ptr, &img_size) == 1)
            {
                LOG_PRINT(LOG_DEBUG, "Hit Color Image Cache[Key: %s, len: %d].", cache_key, img_size);
                status = MagickReadImageBlob(magick_wand, buff_ptr, img_size);
                free(buff_ptr);
                buff_ptr = NULL;
                if(status == MagickFalse)
                {
                    LOG_PRINT(LOG_DEBUG, "Color Image Cache[Key: %s] is Bad. Remove.", cache_key);
                    del_cache(req->thr_arg, cache_key);
                }
                else
                {
                    got_color = true;
                    LOG_PRINT(LOG_DEBUG, "Read Image from Color Image Cache[Key: %s, len: %d] Succ. Goto Convert.", cache_key, img_size);
                    goto convert;
                }
            }

            status=MagickReadImage(magick_wand, color_path);
            if(status == MagickTrue)
            {
                got_color = true;
                LOG_PRINT(LOG_DEBUG, "Read Image from Color Image[%s] Succ. Goto Convert.", rsp_path);
                buff_ptr = (char *)MagickGetImageBlob(magick_wand, &img_size);
                if(img_size < CACHE_MAX_SIZE)
                {
                    set_cache_bin(req->thr_arg, cache_key, buff_ptr, img_size);
                }
                free(buff_ptr);
                buff_ptr = NULL;

                goto convert;
            }
        }

        // to gen cache_key like this: rsp_path-/926ee2f570dc50b2575e35a6712b08ce
        gen_key(cache_key, req->md5, 0);
        if(find_cache_bin(req->thr_arg, cache_key, &buff_ptr, &img_size) == 1)
        {
            LOG_PRINT(LOG_DEBUG, "Hit Orignal Image Cache[Key: %s].", cache_key);
            status = MagickReadImageBlob(magick_wand, buff_ptr, img_size);
            free(buff_ptr);
            buff_ptr = NULL;
            if(status == MagickFalse)
            {
                LOG_PRINT(LOG_DEBUG, "Open Original Image From Blob Failed! Begin to Open it From Disk.");
                ThrowWandException(magick_wand);
                del_cache(req->thr_arg, cache_key);
                status = MagickReadImage(magick_wand, orig_path);
                if(status == MagickFalse)
                {
                    ThrowWandException(magick_wand);
                    goto err;
                }
                else
                {
                    buff_ptr = (char *)MagickGetImageBlob(magick_wand, &img_size);
                    if(img_size < CACHE_MAX_SIZE)
                    {
                        set_cache_bin(req->thr_arg, cache_key, buff_ptr, img_size);
                    }
                    free(buff_ptr);
                    buff_ptr = NULL;
                }
            }
        }
        else
        {
            LOG_PRINT(LOG_DEBUG, "Not Hit Original Image Cache. Begin to Open it.");
            status = MagickReadImage(magick_wand, orig_path);
            if(status == MagickFalse)
            {
                ThrowWandException(magick_wand);
                goto err;
            }
            else
            {
                buff_ptr = (char *)MagickGetImageBlob(magick_wand, &img_size);
                if(img_size < CACHE_MAX_SIZE)
                {
                    set_cache_bin(req->thr_arg, cache_key, buff_ptr, img_size);
                }
                free(buff_ptr);
                buff_ptr = NULL;
            }
        }

        int width, height;
        width = req->width;
        height = req->height;
        if(width == 0 && height == 0)
        {
            LOG_PRINT(LOG_DEBUG, "Image[%s] needn't resize. Goto Convert.", orig_path);
            goto convert;
        }
        float owidth = MagickGetImageWidth(magick_wand);
        float oheight = MagickGetImageHeight(magick_wand);
        if(width <= owidth && height <= oheight)
        {
            if(req->proportion == 1 || (req->proportion == 0 && req->width * req->height == 0))
            {
                if(req->height == 0)
                {
                    height = width * oheight / owidth;
                }
                else
                {
                    width = height * owidth / oheight;
                }
            }
            status = MagickResizeImage(magick_wand, width, height, LanczosFilter, 1.0);
            if(status == MagickFalse)
            {
                LOG_PRINT(LOG_DEBUG, "Image[%s] Resize Failed!", orig_path);
                goto err;
            }
            LOG_PRINT(LOG_DEBUG, "Resize img succ.");
        }
        else
        {
            // Note this strcpy because rsp_path is not useful. We needn't to save the new image.
            got_rsp = true;
            LOG_PRINT(LOG_DEBUG, "Args width/height is bigger than real size, return original image.");
        }
    }
    else
    {
        fstat(fd, &f_stat);
        size_t rlen = 0;
        img_size = f_stat.st_size;
        if(img_size <= 0)
        {
            LOG_PRINT(LOG_DEBUG, "File[%s] is Empty.", rsp_path);
            goto err;
        }
        if((buff_ptr = (char *)malloc(img_size)) == NULL)
        {
            LOG_PRINT(LOG_DEBUG, "buff_ptr Malloc Failed!");
            goto err;
        }
        LOG_PRINT(LOG_DEBUG, "img_size = %d", img_size);
        if((rlen = read(fd, buff_ptr, img_size)) == -1)
        {
            LOG_PRINT(LOG_DEBUG, "File[%s] Read Failed.", rsp_path);
            LOG_PRINT(LOG_DEBUG, "Error: %s.", strerror(errno));
            goto err;
        }
        else if(rlen < img_size)
        {
            LOG_PRINT(LOG_DEBUG, "File[%s] Read Not Compeletly.", rsp_path);
            goto err;
        }
        if(img_size < CACHE_MAX_SIZE)
        {
            set_cache_bin(req->thr_arg, cache_key, buff_ptr, img_size);
        }
        goto done;
    }

convert:

    if(got_color == false)
    {
        //compress image
        LOG_PRINT(LOG_DEBUG, "Start to Compress the Image!");
        img_format = MagickGetImageFormat(magick_wand);
        LOG_PRINT(LOG_DEBUG, "Image Format is %s", img_format);
        if(strcmp(img_format, "JPEG") != 0)
        {
            LOG_PRINT(LOG_DEBUG, "Convert Image Format from %s to JPEG.", img_format);
            status = MagickSetImageFormat(magick_wand, "JPEG");
            if(status == MagickFalse)
            {
                LOG_PRINT(LOG_DEBUG, "Image[%s] Convert Format Failed!", orig_path);
            }
            LOG_PRINT(LOG_DEBUG, "Compress Image with JPEGCompression");
            status = MagickSetImageCompression(magick_wand, JPEGCompression);
            if(status == MagickFalse)
            {
                LOG_PRINT(LOG_DEBUG, "Image[%s] Compression Failed!", orig_path);
            }
        }
        size_t quality = MagickGetImageCompressionQuality(magick_wand);
        LOG_PRINT(LOG_DEBUG, "Image Compression Quality is %u.", quality);
        if(quality > WAP_QUALITY)
        {
            quality = WAP_QUALITY;
        }
        LOG_PRINT(LOG_DEBUG, "Set Compression Quality to 75%.");
        status = MagickSetImageCompressionQuality(magick_wand, quality);
        if(status == MagickFalse)
        {
            LOG_PRINT(LOG_DEBUG, "Set Compression Quality Failed!");
        }

        //strip image EXIF infomation
        LOG_PRINT(LOG_DEBUG, "Start to Remove Exif Infomation of the Image...");
        status = MagickStripImage(magick_wand);
        if(status == MagickFalse)
        {
            LOG_PRINT(LOG_DEBUG, "Remove Exif Infomation of the ImageFailed!");
        }

        buff_ptr = (char *)MagickGetImageBlob(magick_wand, &img_size);
        if(buff_ptr == NULL)
        {
            LOG_PRINT(LOG_DEBUG, "Magick Get Image Blob Failed!");
            goto err;
        }
        gen_key(cache_key, req->md5, 3, req->width, req->height, req->proportion);
        if(img_size < CACHE_MAX_SIZE)
        {
            set_cache_bin(req->thr_arg, cache_key, buff_ptr, img_size);
        }
        if(got_rsp == false)
        {
            LOG_PRINT(LOG_DEBUG, "Color Image[%s] is Not Existed. Begin to Save it.", color_path);
            if(new_img(buff_ptr, img_size, color_path) == -1)
            {
                LOG_PRINT(LOG_DEBUG, "Color Image[%s] Save Failed!", color_path);
                LOG_PRINT(LOG_WARNING, "fail save %s", color_path);
            }
        }
        if(req->gray == 1)
        {
            free(buff_ptr);
            buff_ptr = NULL;
        }
        else
        {
            goto done;
        }
    }

    //gray image
    if(req->gray == 1)
    {
        LOG_PRINT(LOG_DEBUG, "Start to Remove Color!");
        status = MagickSetImageColorspace(magick_wand, GRAYColorspace);
        if(status == MagickFalse)
        {
            LOG_PRINT(LOG_DEBUG, "Image[%s] Remove Color Failed!", orig_path);
            goto err;
        }
        LOG_PRINT(LOG_DEBUG, "Image Remove Color Finish!");

        buff_ptr = (char *)MagickGetImageBlob(magick_wand, &img_size);
        if(buff_ptr == NULL)
        {
            LOG_PRINT(LOG_DEBUG, "Magick Get Image Blob Failed!");
            goto err;
        }
        gen_key(cache_key, req->md5, 4, req->width, req->height, req->proportion, req->gray);
        if(img_size < CACHE_MAX_SIZE)
        {
            set_cache_bin(req->thr_arg, cache_key, buff_ptr, img_size);
        }
        if(got_rsp == false)
        {
            if(new_img(buff_ptr, img_size, rsp_path) == -1)
            {
                LOG_PRINT(LOG_DEBUG, "New Image[%s] Save Failed!", rsp_path);
                LOG_PRINT(LOG_WARNING, "fail save %s", rsp_path);
            }
        }
        else
            LOG_PRINT(LOG_DEBUG, "Image Needn't to Storage.", rsp_path);
    }

done:
    result = evbuffer_add(request->buffer_out, buff_ptr, img_size);
    if(result != -1)
    {
        result = 1;
    }

err:
    if(fd != -1)
        close(fd);
    if(magick_wand)
    {
        magick_wand=DestroyMagickWand(magick_wand);
    }
    if(img_format)
        free(img_format);
    if(buff_ptr)
        free(buff_ptr);
    return result;
}
Beispiel #19
0
/**
 * @brief get_img The function of getting a image buffer and it's length.
 *
 * @param req The zimg_req_t from zhttp and it has the params of a request.
 * @param buff_ptr This function return image buffer in it.
 * @param img_size Get_img will change this number to return the size of image buffer.
 *
 * @return ZIMG_OK for success and ZIMG_ERR for fail.
 */
int get_img(zimg_req_t *req, char **buff_ptr, size_t *img_size)
{
    int result = -1;
    char *rsp_path = NULL;
    char *whole_path = NULL;
    char *orig_path = NULL;
    char *color_path = NULL;
    char *img_format = NULL;
    size_t len;
    int fd = -1;
    struct stat f_stat;

    MagickBooleanType status;
    MagickWand *magick_wand = NULL;

    LOG_PRINT(LOG_INFO, "get_img() start processing zimg request...");

    char *cache_key = (char *)malloc(strlen(req->md5) + 32);
    if(cache_key == NULL){
	LOG_PRINT(LOG_INFO, "malloc failed!");
	return ZIMG_ERR;
    }
    // to gen cache_key like this: img:926ee2f570dc50b2575e35a6712b08ce:0:0:1:0
    sprintf(cache_key, "img:%s:%d:%d:%d:%d", req->md5, req->width, req->height, req->proportion, req->gray);
    if(find_cache_bin(cache_key, buff_ptr, img_size) == 1){
	LOG_PRINT(LOG_INFO, "Hit Cache[Key: %s].", cache_key);
	//        sprintf(cache_key, "type:%s:%d:%d:%d:%d", req->md5, req->width, req->height, req->proportion, req->gray);
	//        if(find_cache(cache_key, img_format) == -1)
	//        {
	//            LOG_PRINT(LOG_WARNING, "Cannot Hit Type Cache[Key: %s]. Use jpeg As Default.", cache_key);
	//            strcpy(img_format, "jpeg");
	//        }
	free(cache_key);
	return ZIMG_OK;
    }
    free(cache_key);

    LOG_PRINT(LOG_INFO, "Start to Find the Image...");

    //check img dir
    // /1023/1023/xxxxxxxxxxxxxxx.png
    len = strlen(req->md5) + strlen(settings.img_path) + 12;
    whole_path = malloc(len);

    if (whole_path == NULL){
	LOG_PRINT(LOG_ERROR, "whole_path malloc failed!");
	return ZIMG_ERR;
    }

    int lvl1 = str_hash(req->md5);
    int lvl2 = str_hash(req->md5 + 3);
    sprintf(whole_path, "%s/%d/%d/%s", settings.img_path, lvl1, lvl2, req->md5);
    LOG_PRINT(LOG_INFO, "docroot: %s", settings.img_path);
    LOG_PRINT(LOG_INFO, "req->md5: %s", req->md5);
    LOG_PRINT(LOG_INFO, "whole_path: %s", whole_path);

    char name[128];
    if(req->proportion && req->gray)
	sprintf(name, "%d*%dpg", req->width, req->height);
    else if(req->proportion && !req->gray)
	sprintf(name, "%d*%dp", req->width, req->height);
    else if(!req->proportion && req->gray)
	sprintf(name, "%d*%dg", req->width, req->height);
    else
	sprintf(name, "%d*%d", req->width, req->height);

    orig_path = (char *)malloc(strlen(whole_path) + 6);
    sprintf(orig_path, "%s/0*0p", whole_path);
    LOG_PRINT(LOG_INFO, "0rig File Path: %s", orig_path);

    rsp_path = (char *)malloc(512);
    if(req->width == 0 && req->height == 0 && req->gray == 0)
    {
	LOG_PRINT(LOG_INFO, "Return original image.");
	strcpy(rsp_path, orig_path);
    }
    else
    {
	sprintf(rsp_path, "%s/%s", whole_path, name);
    }
    LOG_PRINT(LOG_INFO, "Got the rsp_path: %s", rsp_path);
    bool got_rsp = true;
    bool got_color = false;


    //status=MagickReadImage(magick_wand, rsp_path);
    if((fd = open(rsp_path, O_RDONLY)) == -1)
	//if(status == MagickFalse)
    {
	magick_wand = NewMagickWand();
	got_rsp = false;

	if(req->gray == 1)
	{
	    sprintf(cache_key, "img:%s:%d:%d:%d:0", req->md5, req->width, req->height, req->proportion);
	    if(find_cache_bin(cache_key, buff_ptr, img_size) == 1)
	    {
		LOG_PRINT(LOG_INFO, "Hit Color Image Cache[Key: %s, len: %d].", cache_key, *img_size);
		status = MagickReadImageBlob(magick_wand, *buff_ptr, *img_size);
		if(status == MagickFalse)
		{
		    LOG_PRINT(LOG_WARNING, "Color Image Cache[Key: %s] is Bad. Remove.", cache_key);
		    del_cache(cache_key);
		}
		else
		{
		    got_color = true;
		    LOG_PRINT(LOG_INFO, "Read Image from Color Image Cache[Key: %s, len: %d] Succ. Goto Convert.", cache_key, *img_size);
		    goto convert;
		}
	    }

	    len = strlen(rsp_path);
	    color_path = (char *)malloc(len);
	    strncpy(color_path, rsp_path, len);
	    color_path[len - 1] = '\0';
	    LOG_PRINT(LOG_INFO, "color_path: %s", color_path);
	    status=MagickReadImage(magick_wand, color_path);
	    if(status == MagickTrue)
	    {
		got_color = true;
		LOG_PRINT(LOG_INFO, "Read Image from Color Image[%s] Succ. Goto Convert.", color_path);
		*buff_ptr = (char *)MagickGetImageBlob(magick_wand, img_size);
		if(*img_size < CACHE_MAX_SIZE)
		{
		    set_cache_bin(cache_key, *buff_ptr, *img_size);
		    //                    img_format = MagickGetImageFormat(magick_wand);
		    //                    sprintf(cache_key, "type:%s:%d:%d:%d:0", req->md5, req->width, req->height, req->proportion);
		    //                    set_cache(cache_key, img_format);
		}

		goto convert;
	    }
	}

	// to gen cache_key like this: rsp_path-/926ee2f570dc50b2575e35a6712b08ce
	sprintf(cache_key, "img:%s:0:0:1:0", req->md5);
	if(find_cache_bin(cache_key, buff_ptr, img_size) == 1)
	{
	    LOG_PRINT(LOG_INFO, "Hit Orignal Image Cache[Key: %s].", cache_key);
	    status = MagickReadImageBlob(magick_wand, *buff_ptr, *img_size);
	    if(status == MagickFalse)
	    {
		LOG_PRINT(LOG_WARNING, "Open Original Image From Blob Failed! Begin to Open it From Disk.");
		ThrowWandException(magick_wand);
		del_cache(cache_key);
		status = MagickReadImage(magick_wand, orig_path);
		if(status == MagickFalse)
		{
		    ThrowWandException(magick_wand);
		    goto err;
		}
		else
		{
		    *buff_ptr = (char *)MagickGetImageBlob(magick_wand, img_size);
		    if(*img_size < CACHE_MAX_SIZE)
		    {
			set_cache_bin(cache_key, *buff_ptr, *img_size);
			//                        img_format = MagickGetImageFormat(magick_wand);
			//                        sprintf(cache_key, "type:%s:0:0:1:0", req->md5);
			//                        set_cache(cache_key, img_format);
		    }
		}
	    }
	}
	else
	{
	    LOG_PRINT(LOG_INFO, "Not Hit Original Image Cache. Begin to Open it.");
	    status = MagickReadImage(magick_wand, orig_path);
	    if(status == MagickFalse)
	    {
		ThrowWandException(magick_wand);
		goto err;
	    }
	    else
	    {
		*buff_ptr = (char *)MagickGetImageBlob(magick_wand, img_size);
		if(*img_size < CACHE_MAX_SIZE)
		{
		    set_cache_bin(cache_key, *buff_ptr, *img_size);
		    //                    img_format = MagickGetImageFormat(magick_wand);
		    //                    sprintf(cache_key, "type:%s:0:0:1:0", req->md5);
		    //                    set_cache(cache_key, img_format);
		}
	    }
	}
	int width, height;
	width = req->width;
	height = req->height;
	float owidth = MagickGetImageWidth(magick_wand);
	float oheight = MagickGetImageHeight(magick_wand);
	if(width <= owidth && height <= oheight)
	{
	    if(req->proportion == 1)
	    {
		if(req->width != 0 && req->height == 0)
		{
		    height = width * oheight / owidth;
		}
		//else if(height != 0 && width == 0)
		else
		{
		    width = height * owidth / oheight;
		}
	    }
	    status = MagickResizeImage(magick_wand, width, height, LanczosFilter, 1.0);
	    if(status == MagickFalse)
	    {
		LOG_PRINT(LOG_ERROR, "Image[%s] Resize Failed!", orig_path);
		goto err;
	    }
	    LOG_PRINT(LOG_INFO, "Resize img succ.");
	}
	/* this section can caculate the correct rsp_path, but not use, so I note them
	   else if(req->gray == true)
	   {
	   strcpy(rsp_path, orig_path);
	   rsp_path[strlen(orig_path)] = 'g';
	   rsp_path[strlen(orig_path) + 1] = '\0';
	   got_rsp = true;
	   LOG_PRINT(LOG_INFO, "Args width/height is bigger than real size, return original gray image.");
	   LOG_PRINT(LOG_INFO, "Original Gray Image: %s", rsp_path);
	   }
	 */
	else
	{
	    // Note this strcpy because rsp_path is not useful. We needn't to save the new image.
	    //strcpy(rsp_path, orig_path);
	    got_rsp = true;
	    LOG_PRINT(LOG_INFO, "Args width/height is bigger than real size, return original image.");
	}
    }
    else
    {
	fstat(fd, &f_stat);
	size_t rlen = 0;
	*img_size = f_stat.st_size;
	if(*img_size <= 0)
	{
	    LOG_PRINT(LOG_ERROR, "File[%s] is Empty.", rsp_path);
	    goto err;
	}
	if((*buff_ptr = (char *)malloc(*img_size)) == NULL)
	{
	    LOG_PRINT(LOG_ERROR, "buff_ptr Malloc Failed!");
	    goto err;
	}
	LOG_PRINT(LOG_INFO, "img_size = %d", *img_size);
	//*buff_ptr = (char *)MagickGetImageBlob(magick_wand, img_size);
	if((rlen = read(fd, *buff_ptr, *img_size)) == -1)
	{
	    LOG_PRINT(LOG_ERROR, "File[%s] Read Failed.", rsp_path);
	    LOG_PRINT(LOG_ERROR, "Error: %s.", strerror(errno));
	    goto err;
	}
	else if(rlen < *img_size)
	{
	    LOG_PRINT(LOG_ERROR, "File[%s] Read Not Compeletly.", rsp_path);
	    goto err;
	}
	goto done;
    }



convert:
    //gray image
    if(req->gray == true)
    {
	LOG_PRINT(LOG_INFO, "Start to Remove Color!");
	status = MagickSetImageColorspace(magick_wand, GRAYColorspace);
	if(status == MagickFalse)
	{
	    LOG_PRINT(LOG_ERROR, "Image[%s] Remove Color Failed!", orig_path);
	    goto err;
	}
	LOG_PRINT(LOG_INFO, "Image Remove Color Finish!");
    }

    if(got_color == false || (got_color == true && req->width == 0) )
    {
	//compress image
	LOG_PRINT(LOG_INFO, "Start to Compress the Image!");
	img_format = MagickGetImageFormat(magick_wand);
	LOG_PRINT(LOG_INFO, "Image Format is %s", img_format);
	if(strcmp(img_format, "JPEG") != 0)
	{
	    LOG_PRINT(LOG_INFO, "Convert Image Format from %s to JPEG.", img_format);
	    status = MagickSetImageFormat(magick_wand, "JPEG");
	    if(status == MagickFalse)
	    {
		LOG_PRINT(LOG_WARNING, "Image[%s] Convert Format Failed!", orig_path);
	    }
	    LOG_PRINT(LOG_INFO, "Compress Image with JPEGCompression");
	    status = MagickSetImageCompression(magick_wand, JPEGCompression);
	    if(status == MagickFalse)
	    {
		LOG_PRINT(LOG_WARNING, "Image[%s] Compression Failed!", orig_path);
	    }
	}
	size_t quality = MagickGetImageCompressionQuality(magick_wand) * 0.75;
	LOG_PRINT(LOG_INFO, "Image Compression Quality is %u.", quality);
	if(quality == 0)
	{
	    quality = 75;
	}
	LOG_PRINT(LOG_INFO, "Set Compression Quality to 75%.");
	status = MagickSetImageCompressionQuality(magick_wand, quality);
	if(status == MagickFalse)
	{
	    LOG_PRINT(LOG_WARNING, "Set Compression Quality Failed!");
	}

	//strip image EXIF infomation
	LOG_PRINT(LOG_INFO, "Start to Remove Exif Infomation of the Image...");
	status = MagickStripImage(magick_wand);
	if(status == MagickFalse)
	{
	    LOG_PRINT(LOG_WARNING, "Remove Exif Infomation of the ImageFailed!");
	}
    }
    *buff_ptr = (char *)MagickGetImageBlob(magick_wand, img_size);
    if(*buff_ptr == NULL)
    {
	LOG_PRINT(LOG_ERROR, "Magick Get Image Blob Failed!");
	goto err;
    }


done:
    if(*img_size < CACHE_MAX_SIZE)
    {
	// to gen cache_key like this: rsp_path-/926ee2f570dc50b2575e35a6712b08ce
	sprintf(cache_key, "img:%s:%d:%d:%d:%d", req->md5, req->width, req->height, req->proportion, req->gray);
	set_cache_bin(cache_key, *buff_ptr, *img_size);
	//        sprintf(cache_key, "type:%s:%d:%d:%d:%d", req->md5, req->width, req->height, req->proportion, req->gray);
	//        set_cache(cache_key, img_format);
    }

    result = 1;
    if(got_rsp == false)
    {
	LOG_PRINT(LOG_INFO, "Image[%s] is Not Existed. Begin to Save it.", rsp_path);
	result = 2;
    }
    else
	LOG_PRINT(LOG_INFO, "Image Needn't to Storage.", rsp_path);

err:
    if(fd != -1)
	close(fd);
    req->rsp_path = rsp_path;
    if(magick_wand)
    {
	magick_wand=DestroyMagickWand(magick_wand);
    }
    if(img_format)
	free(img_format);
    if(cache_key)
	free(cache_key);
    if (orig_path)
	free(orig_path);
    if (whole_path)
	free(whole_path);
    return result;
}
Beispiel #20
0
static void doit(const char *src, const char *dst, size_t oldsize,
                 const struct imgmin_options *opt)
{
    MagickWand *mw, *tmp;
    MagickBooleanType status;
    double ks;
    size_t newsize = oldsize + 1;

    MagickWandGenesis();
    mw = NewMagickWand();

    /* load image... */
    if (0 == strcmp("-", src))
    {
        /* ...from stdin */
        # define BIGBUF (16 * 1024 * 1024)
        char *blob = malloc(BIGBUF);
        oldsize = read(STDIN_FILENO, blob, BIGBUF);
        if (BIGBUF == oldsize)
        {
            fprintf(stderr, "Image too large for hardcoded imgmin stdin buffer\n");
            exit(1);
        }
        MagickReadImageBlob(mw, blob, oldsize);
        free(blob);
    } else {
        /* ...from disk */
        status = MagickReadImage(mw, src);
        if (status == MagickFalse)
            ThrowWandException(mw);
    }
 
    ks = oldsize / 1024.;

    fprintf(stderr,
        "Before quality:%lu colors:%lu size:%5.1fkB type:%s ",
        quality(mw),
        (unsigned long)unique_colors(mw),
        ks, type2str(MagickGetImageType(mw)));

    tmp = search_quality(mw, dst, opt);

    /* output image... */
    {
        unsigned char *blob = MagickGetImageBlob(tmp, &newsize);

        /* if resulting image is larger than original, use original instead */
        if (newsize > oldsize)
        {
            (void) MagickRelinquishMemory(blob);
            blob = MagickGetImageBlob(mw, &newsize);
        }

        {
            int fd;
            if (0 == strcmp("-", dst))
            {
                fd = STDOUT_FILENO;
            } else {
                fd = open(dst, O_WRONLY | O_CREAT, 0644);
                if (-1 == fd)
                {
                    perror("open");
                    exit(1);
                }
            }
            if ((ssize_t)newsize != write(fd, blob, newsize))
            {
                perror("write");
                exit(1);
            }
            (void) MagickRelinquishMemory(blob);
            if (fd != STDOUT_FILENO)
                close(fd);
        }
    }

    {
        double kd = newsize / 1024.;
        double ksave = ks - kd;
        double kpct = ksave * 100. / ks;

        fprintf(stderr,
            "After  quality:%lu colors:%lu size:%5.1fkB saved:%5.1fkB (%.1f%%)\n",
            (unsigned long)quality(tmp),
            (unsigned long)unique_colors(tmp),
            kd, ksave, kpct);
    }

    /* tear it down */
    DestroyMagickWand(tmp);
    DestroyMagickWand(mw);
    MagickWandTerminus();
}
Beispiel #21
0
unsigned char *get_thumbnail(char *full_filename, char *thumbnail_str,
		size_t *thumbnail_size, int is_rotate, int rotate_degree) {

	unsigned char *image_data = NULL;

	if (full_filename == NULL || thumbnail_str == NULL)
	return NULL;
	MagickBooleanType status;
	MagickWand *tmp_magick_wand = NULL;
	MagickWand *magick_wand = NULL;
	magick_wand = NewMagickWand();
	status = MagickReadImage(magick_wand, full_filename);
	if (status == MagickFalse) {
		ThrowWandException(magick_wand);
		return NULL;
	}
	PixelWand *background = NULL;

	size_t height = MagickGetImageHeight(magick_wand);
	size_t old_height = height;
	size_t width = MagickGetImageWidth(magick_wand);
	size_t old_width = width;

	ssize_t i = 0, j = 0;
	int is_crop = 0;
	char is_gif_flag = 0;
	char is_jpeg_flag = 0;
	int do_quality = 0;
	char *fileformat = NULL;

	fileformat = MagickGetImageFormat(magick_wand);
	if (fileformat == NULL) {
		return NULL;
	}

	if (0 == strcasecmp(fileformat, image_format[GIFEXT])) {
		is_gif_flag = 1;
	} else if (0 == strcasecmp(fileformat, image_format[JPEGEXT])) {
		is_jpeg_flag = 1;
	} else if (0 == strcasecmp(fileformat, image_format[JPGEXT])) {
		is_jpeg_flag = 1;
	}
	fileformat = (char *)MagickRelinquishMemory(fileformat); //free();
	if( 'C' == *thumbnail_str ||'c' == *thumbnail_str ) {
		is_crop = 1;
	}
	if(is_crop) {
		ParseMetaGeometry(thumbnail_str + 1, &i, &j, &width, &height);
	} else {
		ParseMetaGeometry(thumbnail_str, &i, &j, &width, &height);
	}

	if (old_width == width && height == old_height) {
		image_data = MagickGetImagesBlob(magick_wand, thumbnail_size);
	} else if (width <= 0 || height <= 0) {
		logError("%s%s:Geometry  %s error\n", __FILE__, __func__, thumbnail_str);
	} else {
		/*
		 * if type of the image is GIF, maybe have more than one frame, so do this different
		 *  from others
		 */
		if (is_gif_flag) {
			tmp_magick_wand = magick_wand;
			magick_wand = MagickCoalesceImages(tmp_magick_wand);
			tmp_magick_wand = DestroyMagickWand(tmp_magick_wand);
		}
		/*
		 * if size of the image less than 800 * 600 and that's type is JPEG, then do
		 * quality 100 OP
		 */
		if ((old_width < 800) && (old_height < 600) && is_jpeg_flag && is_crop != 1) {
			do_quality = 1;
		}

		MagickResetIterator(magick_wand);
		while (MagickNextImage(magick_wand) != MagickFalse) {
			if(do_quality) {
				MagickSetImageCompressionQuality(magick_wand, 100);
				MagickStripImage(magick_wand);
			}
			if(is_crop == 0)
			MagickThumbnailImage(magick_wand, width, height);
			else {
				logInfo("crop Image %ld, %ld", i, j);
				MagickCropImage(magick_wand, width, height, i, j);
			}
			if(is_rotate == 1) {
				background=NewPixelWand();
				status=PixelSetColor(background,"#000000");
				MagickRotateImage(magick_wand, background,(double)rotate_degree);
				background=DestroyPixelWand(background);
			}
		}
		image_data = MagickGetImagesBlob(magick_wand, thumbnail_size);
	}
	magick_wand = DestroyMagickWand(magick_wand);
	return image_data;
}
Beispiel #22
0
int main(int argc, char **argv)
{
	printf("Hello World\n");
#define QuantumScale ((MagickRealType) 1.0/(MagickRealType) QuantumRange)
#define SigmoidalContrast(x) (QuantumRange*(1.0/(1+exp(10.0*(0.5-QuantumScale*x)))-0.0066928509)*1.0092503)

#define ThrowWandException(wand)\
	{\
		char *description;\
		ExceptionType\
		severity;\
		\
		description=MagickGetException(wand,&severity);\
		(void)fprintf(stderr,"%s %s %lu %s\n",GetMagickModule(),description);\
		exit(-1);\
	}
	long y;
	MagickBooleanType status;
	MagickPixelPacket pixel;
	MagickWand *contrast_wand, *image_wand;
	PixelIterator *contrast_iterator,*iterator;
	PixelWand **contrast_pixels, **pixels;
	register long x;
	unsigned long width;

	if (argc != 3)
	{
		(void)fprintf(stdout,"Usage: %s image sigmoidal-image\n",argv[0]);
		exit(0);
	}

	/*
	   Read an Image
	   */

	MagickWandGenesis();
	image_wand = NewMagickWand();
	status = MagickReadImage(image_wand,argv[1]);
	if(status == MagickFalse)
		ThrowWandException(image_wand);
	contrast_wand = CloneMagickWand(image_wand);
	/*
	   Sigmoidal non-linearity contrast control.
	   */

	iterator = NewPixelIterator(image_wand);
	contrast_iterator=NewPixelIterator(contrast_wand);

	if((iterator == (PixelIterator*)NULL) || (contrast_iterator == (PixelIterator*)NULL))
		ThrowWandException(image_wand);

	for(y=0; y<(long)MagickGetImageHeight(image_wand); y++)
	{
		pixels = PixelGetNextIteratorRow(iterator,&width);
		contrast_pixels = PixelGetNextIteratorRow(contrast_iterator,&width);
		if((pixels==(PixelWand**)NULL) || (contrast_pixels == (PixelWand**)NULL))
			break;

		for(x = 0; x<(long)width; x++)
		{
			PixelGetMagickColor(pixels[x],&pixel);
			pixel.red = SigmoidalContrast(pixel.red);
			pixel.green = SigmoidalContrast(pixel.green);
			pixel.blue = SigmoidalContrast(pixel.blue);
			pixel.index = SigmoidalContrast(pixel.index);
			PixelSetMagickColor(contrast_pixels[x],&pixel);
		}
		(void)PixelSyncIterator(contrast_iterator);
	}
	if(y < (long)MagickGetImageHeight(image_wand))
		ThrowWandException(image_wand);
	contrast_iterator = DestroyPixelIterator(contrast_iterator);
	iterator = DestroyPixelIterator(iterator);
	image_wand=DestroyMagickWand(image_wand);

	status = MagickWriteImages(contrast_wand,argv[2],MagickTrue);
	if(status == MagickFalse)
		ThrowWandException(image_wand);
	contrast_wand = DestroyMagickWand(contrast_wand);
	MagickWandTerminus();
	return 0;
}
Beispiel #23
0
/**
 * @brief get_img_mode_db Get image from db mode backend.
 *
 * @param req zimg request struct
 * @param buff_ptr buff pointer
 * @param img_size buff size
 *
 * @return 1 for success and -1 for failed
 */
int get_img_mode_db(zimg_req_t *req, evhtp_request_t *request)
{
    int result = -1;
    char cache_key[CACHE_KEY_SIZE];
    char *img_format = NULL;
    char *buff_ptr = NULL;
    size_t img_size;

    MagickBooleanType status;
    MagickWand *magick_wand = NULL;

    bool got_rsp = true;
    bool got_color = false;

    LOG_PRINT(LOG_DEBUG, "get_img() start processing zimg request...");

    if(req->gray == 1)
    {
        gen_key(cache_key, req->md5, 4, req->width, req->height, req->proportion, req->gray);
    }
    else
    {
        if(req->proportion == 0 && req->width == 0 && req->height == 0)
        {
            gen_key(cache_key, req->md5, 0);
        }
        else
        {
            gen_key(cache_key, req->md5, 3, req->width, req->height, req->proportion);
        }
    }
    if(find_cache_bin(req->thr_arg, cache_key, &buff_ptr, &img_size) == 1)
    {
        LOG_PRINT(LOG_DEBUG, "Hit Cache[Key: %s].", cache_key);
        goto done;
    }
    LOG_PRINT(LOG_DEBUG, "Start to Find the Image...");
    if(get_img_db(req->thr_arg, cache_key, &buff_ptr, &img_size) == 1)
    {
        LOG_PRINT(LOG_DEBUG, "Get image [%s] from backend db succ.", cache_key);
        if(img_size < CACHE_MAX_SIZE)
        {
            set_cache_bin(req->thr_arg, cache_key, buff_ptr, img_size);
        }
        goto done;
    }

    magick_wand = NewMagickWand();
    got_rsp = false;
    if(req->gray == 1)
    {
        gen_key(cache_key, req->md5, 3, req->width, req->height, req->proportion);
        if(find_cache_bin(req->thr_arg, cache_key, &buff_ptr, &img_size) == 1)
        {
            LOG_PRINT(LOG_DEBUG, "Hit Color Image Cache[Key: %s, len: %d].", cache_key, img_size);
            status = MagickReadImageBlob(magick_wand, buff_ptr, img_size);
            free(buff_ptr);
            buff_ptr = NULL;
            if(status == MagickFalse)
            {
                LOG_PRINT(LOG_DEBUG, "Color Image Cache[Key: %s] is Bad. Remove.", cache_key);
                del_cache(req->thr_arg, cache_key);
            }
            else
            {
                got_color = true;
                LOG_PRINT(LOG_DEBUG, "Read Image from Color Image Cache[Key: %s, len: %d] Succ. Goto Convert.", cache_key, img_size);
                goto convert;
            }
        }
        if(get_img_db(req->thr_arg, cache_key, &buff_ptr, &img_size) == 1)
        {
            LOG_PRINT(LOG_DEBUG, "Get color image [%s] from backend db.", cache_key);
            status = MagickReadImageBlob(magick_wand, buff_ptr, img_size);
            if(status == MagickTrue)
            {
                got_color = true;
                LOG_PRINT(LOG_DEBUG, "Read Image from Color Image[%s] Succ. Goto Convert.", cache_key);
                if(img_size < CACHE_MAX_SIZE)
                {
                    set_cache_bin(req->thr_arg, cache_key, buff_ptr, img_size);
                }
                free(buff_ptr);
                buff_ptr = NULL;
                goto convert;
            }
        }
    }

    gen_key(cache_key, req->md5, 0);
    if(find_cache_bin(req->thr_arg, cache_key, &buff_ptr, &img_size) == 1)
    {
        LOG_PRINT(LOG_DEBUG, "Hit Cache[Key: %s].", cache_key);
    }
    else
    {
        if(get_img_db(req->thr_arg, cache_key, &buff_ptr, &img_size) == -1)
        {
            LOG_PRINT(LOG_DEBUG, "Get image [%s] from backend db failed.", cache_key);
            goto err;
        }
        else if(img_size < CACHE_MAX_SIZE)
        {
            set_cache_bin(req->thr_arg, cache_key, buff_ptr, img_size);
        }
    }

    status = MagickReadImageBlob(magick_wand, buff_ptr, img_size);
    free(buff_ptr);
    buff_ptr = NULL;
    if(status == MagickFalse)
    {
        ThrowWandException(magick_wand);
        del_cache(req->thr_arg, cache_key);
        LOG_PRINT(LOG_DEBUG, "Read image [%s] from blob failed.", cache_key);
        goto err;
    }

    if(req->width == 0 && req->height == 0)
    {
        LOG_PRINT(LOG_DEBUG, "Image [%s] needn't resize. Goto Convert.", cache_key);
        goto convert;
    }

    int width, height;
    width = req->width;
    height = req->height;
    float owidth = MagickGetImageWidth(magick_wand);
    float oheight = MagickGetImageHeight(magick_wand);
    if(width <= owidth && height <= oheight)
    {
        if(req->proportion == 1 || (req->proportion == 0 && req->width * req->height == 0))
        {
            if(req->height == 0)
            {
                height = width * oheight / owidth;
            }
            else
            {
                width = height * owidth / oheight;
            }
        }
        status = MagickResizeImage(magick_wand, width, height, LanczosFilter, 1.0);
        if(status == MagickFalse)
        {
            LOG_PRINT(LOG_DEBUG, "Image[%s] Resize Failed!", cache_key);
            goto err;
        }

        LOG_PRINT(LOG_DEBUG, "Resize img succ.");
    }
    else
    {
        got_rsp = true;
        LOG_PRINT(LOG_DEBUG, "Args width/height is bigger than real size, return original image.");
    }

convert:

    //compress image
    if(got_color == false)
    {
        LOG_PRINT(LOG_DEBUG, "Start to Compress the Image!");
        img_format = MagickGetImageFormat(magick_wand);
        LOG_PRINT(LOG_DEBUG, "Image Format is %s", img_format);
        if(strcmp(img_format, "JPEG") != 0)
        {
            LOG_PRINT(LOG_DEBUG, "Convert Image Format from %s to JPEG.", img_format);
            status = MagickSetImageFormat(magick_wand, "JPEG");
            if(status == MagickFalse)
            {
                LOG_PRINT(LOG_DEBUG, "Image[%s] Convert Format Failed!", cache_key);
            }
            LOG_PRINT(LOG_DEBUG, "Compress Image with JPEGCompression");
            status = MagickSetImageCompression(magick_wand, JPEGCompression);
            if(status == MagickFalse)
            {
                LOG_PRINT(LOG_DEBUG, "Image[%s] Compression Failed!", cache_key);
            }
        }
        size_t quality = MagickGetImageCompressionQuality(magick_wand);
        LOG_PRINT(LOG_DEBUG, "Image Compression Quality is %u.", quality);
        if(quality > WAP_QUALITY)
        {
            quality = WAP_QUALITY;
        }
        LOG_PRINT(LOG_DEBUG, "Set Compression Quality to 75%.");
        status = MagickSetImageCompressionQuality(magick_wand, quality);
        if(status == MagickFalse)
        {
            LOG_PRINT(LOG_DEBUG, "Set Compression Quality Failed!");
        }

        //strip image EXIF infomation
        LOG_PRINT(LOG_DEBUG, "Start to Remove Exif Infomation of the Image...");
        status = MagickStripImage(magick_wand);
        if(status == MagickFalse)
        {
            LOG_PRINT(LOG_DEBUG, "Remove Exif Infomation of the ImageFailed!");
        }

        buff_ptr = (char *)MagickGetImageBlob(magick_wand, &img_size);
        if(buff_ptr == NULL)
        {
            LOG_PRINT(LOG_DEBUG, "Magick Get Image Blob Failed!");
            goto err;
        }
        gen_key(cache_key, req->md5, 3, req->width, req->height, req->proportion);
        if(got_rsp == false)
        {
            save_img_db(req->thr_arg, cache_key, buff_ptr, img_size);
        }
        if(img_size < CACHE_MAX_SIZE)
        {
            set_cache_bin(req->thr_arg, cache_key, buff_ptr, img_size);
        }
        if(req->gray == 1)
        {
            free(buff_ptr);
            buff_ptr = NULL;
        }
        else
        {
            goto done;
        }
    } 

    //gray image
    if(req->gray == 1)
    {
        LOG_PRINT(LOG_DEBUG, "Start to Remove Color!");
        status = MagickSetImageColorspace(magick_wand, GRAYColorspace);
        if(status == MagickFalse)
        {
            LOG_PRINT(LOG_DEBUG, "Image[%s] Remove Color Failed!", cache_key);
            goto err;
        }
        LOG_PRINT(LOG_DEBUG, "Image Remove Color Finish!");


        buff_ptr = (char *)MagickGetImageBlob(magick_wand, &img_size);
        if(buff_ptr == NULL)
        {
            LOG_PRINT(LOG_DEBUG, "Magick Get Image Blob Failed!");
            goto err;
        }
        gen_key(cache_key, req->md5, 4, req->width, req->height, req->proportion, req->gray);
        if(got_rsp == false)
        {
            save_img_db(req->thr_arg, cache_key, buff_ptr, img_size);
        }
        if(img_size < CACHE_MAX_SIZE)
        {
            set_cache_bin(req->thr_arg, cache_key, buff_ptr, img_size);
        }
    }

done:
    result = evbuffer_add(request->buffer_out, buff_ptr, img_size);
    if(result != -1)
    {
        result = 1;
    }

err:
    if(magick_wand)
    {
        magick_wand=DestroyMagickWand(magick_wand);
    }
    if(img_format)
        free(img_format);
    if(buff_ptr)
        free(buff_ptr);
    return result;
}
Beispiel #24
0
int main(int argc, char *argv[])
{
  MagickWand
    *wand,
    *input,
    *output;

  MagickBooleanType
    status;

  printf("Add 3 sets of images after setting 'first' on empty wand\n");
  printf("Result shoud be: 678 345 012\n");

  MagickWandGenesis();

  wand = NewMagickWand();
  input = NewMagickWand();

  MagickSetFirstIterator(wand);

  status = MagickReadImage(input, "font_0.gif" )
        && MagickReadImage(input, "font_1.gif" )
        && MagickReadImage(input, "font_2.gif" );
  if (status == MagickFalse)
    ThrowWandException(input);

  status = MagickAddImage(wand, input);
  if (status == MagickFalse)
    ThrowWandException(wand);

  ClearMagickWand(input);
  status = MagickReadImage(input, "font_3.gif" )
        && MagickReadImage(input, "font_4.gif" )
        && MagickReadImage(input, "font_5.gif" );
  if (status == MagickFalse)
    ThrowWandException(input);

  status = MagickAddImage(wand, input);
  if (status == MagickFalse)
    ThrowWandException(wand);

  ClearMagickWand(input);
  status = MagickReadImage(input, "font_6.gif" )
        && MagickReadImage(input, "font_7.gif" )
        && MagickReadImage(input, "font_8.gif" );
  if (status == MagickFalse)
    ThrowWandException(input);


  status = MagickAddImage(wand, input);
  if (status == MagickFalse)
    ThrowWandException(wand);
  input=DestroyMagickWand(input);  /* finished */

  /* append all images together to create the output wand */
  MagickResetIterator(wand); /* append all images */
  output = MagickAppendImages(wand,MagickFalse);
  wand = DestroyMagickWand(wand);  /* finished - could swap here */

  /* Final output */
  status = MagickWriteImage(output,"show:");
  if (status == MagickFalse)
    ThrowWandException(output);

  output = DestroyMagickWand(output);

  MagickWandTerminus();
}