Exemple #1
0
void* magickminify(void* src, ssize_t src_len, ssize_t* dst_len){
  Image *image, *resize;
  ImageInfo image_info;
  ExceptionInfo *exception;
  size_t len;
  void *ans;

  GetImageInfo(&image_info);
  exception = AcquireExceptionInfo();

  image = BlobToImage(&image_info, src, src_len, exception);

  if (exception->severity != UndefinedException)
    CatchException(exception);
  if (image == (Image *) NULL)
    exit(1);

  resize = MinifyImage(image, exception);

  if (exception->severity != UndefinedException)
    CatchException(exception);
  if (image == (Image *) NULL)
    exit(1);

  ans = ImageToBlob(&image_info, resize, &len, exception);
  
  if(dst_len != NULL)
    *dst_len = len;

  DestroyImage(image);
  DestroyImage(resize);
  DestroyExceptionInfo(exception);

  return ans;
}
Image		*get_image_from_path(char *path)
{
    ImageInfo	*image_info;
    Image		*img = NULL;
    ExceptionInfo	exception;
    
    GetExceptionInfo(&exception);
    if ((image_info = CloneImageInfo((ImageInfo *)NULL)) == NULL) {
        CatchException(&exception);
        DestroyImageInfo(image_info);
        DestroyImage(img);
        return (NULL);
    }
    
    strcpy(image_info->filename, path);
    
    if ((img = ReadImage(image_info, &exception)) == NULL)
    {
        CatchException(&exception);
        DestroyImageInfo(image_info);
        DestroyImage(img);
        return (NULL);
    }
    DestroyImageInfo(image_info);
    return (img);
}
/*----------------------------------------------------------------------- */
SEXP
lib_writeImages (SEXP x, SEXP files, SEXP quality) {
    int nz, nfiles, i;
    Image * images, * image;
    ImageInfo *image_info;
    ExceptionInfo exception;

    /* basic checks */
    validImage(x,0);

    images = sexp2Magick (x);
    nz = GetImageListLength(images);
 
    nfiles = LENGTH (files);
    if ( nfiles != 1 && nfiles != nz)
        error ( "number of files must be 1, or equal to the size of the image stack" );
    
    if ( images == NULL || GetImageListLength (images) < 1 )
        error ( "cannot write an empty image" );
    GetExceptionInfo (&exception);
    image_info = CloneImageInfo ( (ImageInfo *)NULL );
    /* set attributes in image_info*/
    image_info->compression = images->compression;
    image_info->quality = (unsigned int) INTEGER (quality)[0];
    if ( nfiles == 1 ) {
    /* save into a single file, TIFF, GIF, or automatically add file suffixes */
        strcpy (image_info->filename, CHAR(STRING_ELT(files, 0)) );
        /* we want to overwrite the feature imported from SEXP image */
        strcpy (images->filename, image_info->filename);
        WriteImages(image_info, images, CHAR(STRING_ELT(files, 0)), &exception);
        CatchException (&exception);
    }
    else {
    /* save each frame into a separate file */
        for ( i = 0; i < nz; i++ ) {
            image = GetImageFromList (images, i);
            if ( image == NULL || GetImageListLength (image) < 1 ) {
                warning ( "cannot write an empty image, skipping" );
                continue;
            }
            strcpy (image_info->filename, CHAR(STRING_ELT(files, i)));
            /* we want to overwrite the feature imported from SEXP image */
            strcpy (image->filename, image_info->filename);
            WriteImage (image_info, image);
            CatchException (&image->exception);
            // WriteImages(image_info, image, CHAR(STRING_ELT(files, i)), &exception);
            // CatchException (&exception);

        }
    }

    image_info = DestroyImageInfo (image_info);
    images = DestroyImageList (images);
    DestroyExceptionInfo(&exception);
    return R_NilValue;
}
Image		*get_blue_channe_image(Image *img)
{
  unsigned int	i = 0;
  unsigned int	j = 0;
  PixelPacket	*px_original;
  PixelPacket	*px_new;
  Image		*new_img;
  ExceptionInfo	exception;
  ImageInfo	*new_img_info;

  GetExceptionInfo(&exception);
  if ((new_img_info = CloneImageInfo((ImageInfo *)NULL)) == NULL) {
    CatchException(&exception);
    DestroyImageInfo(new_img_info);
    return (NULL);
  }

  new_img_info->colorspace = RGBColorspace;
  new_img = AllocateImage(new_img_info);
  new_img->rows = img->rows;
  new_img->columns = img->columns;

  if ((px_original = GetImagePixelsEx(img, 0, 0, img->columns, img->rows, &exception)) == NULL)
    {
      DestroyImage(new_img);
      CatchException(&exception);
      return (NULL);
    }

  if ((px_new = SetImagePixelsEx(new_img, 0, 0, new_img->columns, new_img->rows, &exception)) == NULL)
    {
      DestroyImage(new_img);
      CatchException(&exception);
      return (NULL);
    }

  while (i < img->rows)
    {
      j = 0;
      while (j < img->columns)
	{
	  px_new[(new_img->columns * i) + j].red = 0;
	  px_new[(new_img->columns * i) + j].blue = px_original[(img->columns * i) + j].blue;
	  px_new[(new_img->columns * i) + j].green = 0;
	  j++;
	}
      i++;
    }
  SyncImagePixels(new_img);

  DestroyImageInfo(new_img_info);

  return (new_img);
}
Image *crop_image(Image *img, char *path, int image_width, int image_height, int width_offset, int height_offset)
{
    Image           *new_img = NULL;
    ImageInfo       *image_info;
    Image           *tmp;
    RectangleInfo   *portion;
    ExceptionInfo   exception;


    portion = malloc(sizeof(*portion));
    portion->width = image_width;
    portion->height = image_height;
    portion->x = width_offset;
    portion->y = height_offset;
    
    
    GetExceptionInfo(&exception);
    if ((image_info = CloneImageInfo((ImageInfo *)NULL)) == NULL) {
        CatchException(&exception);
        DestroyImageInfo(image_info);
        free(portion);
        return (NULL);
    }
    
    strcpy(image_info->filename, path);
    
    if ((new_img = ReadImage(image_info, &exception)) == NULL)
    {
        CatchException(&exception);
        DestroyImage(new_img);
        DestroyImageInfo(image_info);
        free(portion);
        return (NULL);
    }
    tmp = new_img;
    
    if ((new_img = CropImage(img, portion, &exception)) == NULL) {
        CatchException(&exception);
        DestroyImage(tmp);
        DestroyImageInfo(image_info);
        free(portion);
        return (NULL);
    }
    
    DestroyImage(img);
    DestroyImage(tmp);
    DestroyImageInfo(image_info);
    free(portion);
    SyncImagePixels(new_img);
    free(path);
    return (new_img);
}
bool ScImgDataLoader_GMagick::preloadAlphaChannel(const QString& fn, int /*page*/, int res, bool& hasAlpha)
{
	initGraphicsMagick();
	initialize();
	hasAlpha = false;

	if (!QFile::exists(fn))
		return false;

	ExceptionInfo exception;
	GetExceptionInfo(&exception);
	ImageInfo *image_info = CloneImageInfo(0);
	strcpy(image_info->filename, fn.toUtf8().data());
	image_info->units = PixelsPerInchResolution;
	Image *image = PingImage(image_info, &exception);
	if (exception.severity != UndefinedException)
		CatchException(&exception);
	if (!image) {
		qCritical() << "Failed to read image" << fn;
		return false;
	}

	hasAlpha = image->matte;
	if (!hasAlpha) return true;
	return loadPicture(fn, 0, 0, false);
}
Exemple #7
0
static
ERL_NIF_TERM exmagick_image_load_blob (ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[])
{
  ErlNifBinary blob;
  exm_resource_t *resource;

  EXM_INIT;
  ErlNifResourceType *type = (ErlNifResourceType *) enif_priv_data(env);

  if (0 == enif_get_resource(env, argv[0], type, (void **) &resource))
  { EXM_FAIL(ehandler, "invalid handle"); }

  if (0 == enif_inspect_binary(env, argv[1], &blob))
  { EXM_FAIL(ehandler, "argv[1]: bad argument"); }

  if (resource->image != NULL)
  {
    DestroyImage(resource->image);
    resource->image = NULL;
  }

  resource->image = BlobToImage(resource->i_info, blob.data, blob.size, &resource->e_info);
  if (resource->image == NULL)
  {
    CatchException(&resource->e_info);
    EXM_FAIL(ehandler, resource->e_info.reason);
  }

  return(enif_make_tuple2(env, enif_make_atom(env, "ok"), argv[0]));

ehandler:
  return(enif_make_tuple2(env, enif_make_atom(env, "error"), exmagick_make_utf8str(env, errmsg)));
}
Exemple #8
0
static
ERL_NIF_TERM exmagick_image_dump_file (ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[])
{
  char filename[MaxTextExtent];
  ErlNifBinary utf8;
  exm_resource_t *resource;

  EXM_INIT;
  ErlNifResourceType *type = (ErlNifResourceType *) enif_priv_data(env);

  if (0 == enif_get_resource(env, argv[0], type, (void **) &resource))
  { EXM_FAIL(ehandler, "invalid handle"); }

  if (0 == exmagick_get_utf8str(env, argv[1], &utf8))
  { EXM_FAIL(ehandler, "argv[1]: bad argument"); }

  exmagick_utf8strcpy (filename, &utf8, MaxTextExtent);
  if (0 == WriteImages(resource->i_info, resource->image, filename, &resource->e_info))
  {
    CatchException(&resource->e_info);
    EXM_FAIL(ehandler, resource->e_info.reason);
  }

  return(enif_make_tuple2(env, enif_make_atom(env, "ok"), argv[0]));

ehandler:
  return(enif_make_tuple2(env, enif_make_atom(env, "error"), exmagick_make_utf8str(env, errmsg)));
}
Exemple #9
0
static
ERL_NIF_TERM exmagick_image_dump_blob (ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[])
{
  void *blob;
  size_t size;
  exm_resource_t *resource;

  EXM_INIT;
  ErlNifResourceType *type = (ErlNifResourceType *) enif_priv_data(env);

  if (0 == enif_get_resource(env, argv[0], type, (void **) &resource))
  { EXM_FAIL(ehandler, "invalid handle"); }

  blob = ImageToBlob(resource->i_info, resource->image, &size, &resource->e_info);
  if (NULL == blob)
  {
    CatchException(&resource->e_info);
    EXM_FAIL(ehandler, resource->e_info.reason);
  }

  return(enif_make_tuple2(env,
                          enif_make_atom(env, "ok"),
                          enif_make_resource_binary(env, resource, blob, size)));
ehandler:
  return(enif_make_tuple2(env, enif_make_atom(env, "error"), exmagick_make_utf8str(env, errmsg)));
}
void ScImgDataLoader_GMagick::loadEmbeddedProfile(const QString& fn, int /*page*/)
{
	initGraphicsMagick();
	m_embeddedProfile.resize(0);
	m_profileComponents = 0;
	if (!QFile::exists(fn)) return;

	ExceptionInfo exception;
	GetExceptionInfo(&exception);
	ImageInfo *image_info = CloneImageInfo(0);
	strcpy(image_info->filename, fn.toUtf8().data());
	image_info->units = PixelsPerInchResolution;
	Image *image = ReadImage(image_info, &exception);
	if (exception.severity != UndefinedException)
		CatchException(&exception);
	if (!image) {
		qCritical() << "Failed to read image" << fn;
		return;
	}

	size_t length = 0;
	const unsigned char *src = GetImageProfile(image, "ICM", &length);
	char *dest = m_embeddedProfile.data();

	if (image->colorspace == CMYKColorspace) {
		m_profileComponents = 4;
	} else if (image->colorspace == RGBColorspace) {
		m_profileComponents = 3;
	}

	m_embeddedProfile.resize(length);
	memcpy(dest, src, length);
}
Exemple #11
0
int main ( int argc, char **argv )
{
  Image *canvas = (Image *)NULL;
  char outfile[MaxTextExtent];
  int rows, columns = 0;
  char size[MaxTextExtent];
  ImageInfo *image_info;
  ExceptionInfo exception;

  if ( argc != 2 )
    {
      (void) printf ( "Usage: %s filename\n", argv[0] );
      exit( 1 );
    }

  outfile[MaxTextExtent-1]='\0';
  (void) strncpy( outfile, argv[1], MaxTextExtent-1 );

  if (LocaleNCompare("drawtest",argv[0],7) == 0)
    InitializeMagick((char *) NULL);
  else
    InitializeMagick(*argv);

  /*
   * Create canvas image
   */
  columns=596;
  rows=842;
  image_info=CloneImageInfo((ImageInfo*)NULL);
  GetExceptionInfo( &exception );
  FormatString(size, "%dx%d", columns, rows);
  (void) CloneString(&image_info->size, size);
  (void) strcpy( image_info->filename, "xc:white");
  canvas = ReadImage ( image_info, &exception );
  if (exception.severity != UndefinedException)
    CatchException(&exception);
  if ( canvas == (Image *)NULL )
    {
      (void) printf ( "Failed to read canvas image %s\n", image_info->filename );
      exit(1);
    }

  /*
   * Scribble on image
   */
  ScribbleImage( canvas );

  /*
   * Save image to file
   */
  canvas->filename[MaxTextExtent-1]='\0';
  (void) strncpy( canvas->filename, outfile, MaxTextExtent-1);
  (void) WriteImage ( image_info, canvas );

  DestroyExceptionInfo( &exception );
  DestroyImage( canvas );
  DestroyImageInfo( image_info );
  DestroyMagick();
  return 0;
}
bool ScImgDataLoader_GMagick::readCMYK(Image *input, RawImage *output, int width, int height)
{
	/* Mapping:
		red:     cyan
		green:   magenta
		blue:    yellow
		opacity: black
		index:   alpha
	*/
	//Copied from GraphicsMagick header and modified
	#define GetCyanSample(p) (p.red)
	#define GetMagentaSample(p) (p.green)
	#define GetYellowSample(p) (p.blue)
	#define GetCMYKBlackSample(p) (p.opacity)
	#define GetAlphaSample(p) (p)

	bool hasAlpha = input->matte;

	if (!output->create(width, height, hasAlpha ? 5 : 4)) return false;

	ExceptionInfo exception;
	GetExceptionInfo(&exception);
	const PixelPacket *pixels = AcquireImagePixels(input, 0, 0, width, height, &exception);
	if (exception.severity != UndefinedException)
		CatchException(&exception);
	if (!pixels) {
		qCritical() << QObject::tr("Could not get pixel data!");
		return false;
	}

    const IndexPacket *alpha = 0;
    if (hasAlpha) {
        alpha = AccessImmutableIndexes(input);
        if (!alpha) {
            qCritical() << QObject::tr("Could not get alpha channel data!");
            return false;
        }
    }

	unsigned char *buffer = output->bits();
	if (!buffer) {
	   qCritical() << QObject::tr("Could not allocate output buffer!");
	   return false;
    }

	int i;
	for (i = 0; i < width*height; i++) {
		*buffer++ = ScaleQuantumToChar(GetCyanSample(pixels[i]));
		*buffer++ = ScaleQuantumToChar(GetMagentaSample(pixels[i]));
		*buffer++ = ScaleQuantumToChar(GetYellowSample(pixels[i]));
		*buffer++ = ScaleQuantumToChar(GetCMYKBlackSample(pixels[i]));
		if (hasAlpha) {
			*buffer++ = 255 - ScaleQuantumToChar(GetAlphaSample(alpha[i]));
		}
	}
	return true;
}
Exemple #13
0
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                                             %
%                                                                             %
%                                                                             %
%   V a l i d a t e I d e n t i f y C o m m a n d                             %
%                                                                             %
%                                                                             %
%                                                                             %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  ValidateIdentifyCommand() validates the ImageMagick identify command line
%  program and returns the number of validation tests that passed and failed.
%
%  The format of the ValidateIdentifyCommand method is:
%
%      unsigned long ValidateIdentifyCommand(ImageInfo *image_info,
%        const char *reference_filename,const char *output_filename,
%        unsigned long *fail,ExceptionInfo *exception)
%
%  A description of each parameter follows:
%
%    o image_info: the image info.
%
%    o reference_filename: the reference image filename.
%
%    o output_filename: the output image filename.
%
%    o fail: return the number of validation tests that pass.
%
%    o exception: return any errors or warnings in this structure.
%
*/
static unsigned long ValidateIdentifyCommand(ImageInfo *image_info,
  const char *reference_filename,const char *output_filename,
  unsigned long *fail,ExceptionInfo *exception)
{
  char
    **arguments,
    command[MaxTextExtent];

  int
    number_arguments;

  MagickBooleanType
    status;

  register long
    i,
    j;

  unsigned long
    test;

  (void) output_filename;
  test=0;
  (void) fprintf(stdout,"validate identify command line program:\n");
  for (i=0; identify_options[i] != (char *) NULL; i++)
  {
    CatchException(exception);
    (void) fprintf(stdout,"  test %lu: %s",test++,identify_options[i]);
    (void) FormatMagickString(command,MaxTextExtent,"%s %s",
      identify_options[i],reference_filename);
    arguments=StringToArgv(command,&number_arguments);
    if (arguments == (char **) NULL)
      {
        (void) fprintf(stdout,"... fail @ %s/%s/%lu.\n",GetMagickModule());
        (*fail)++;
        continue;
      }
    status=IdentifyImageCommand(image_info,number_arguments,arguments,
      (char **) NULL,exception);
    for (j=0; j < number_arguments; j++)
      arguments[j]=DestroyString(arguments[j]);
    arguments=(char **) RelinquishMagickMemory(arguments);
    if (status != MagickFalse)
      {
        (void) fprintf(stdout,"... fail @ %s/%s/%lu.\n",GetMagickModule());
        (*fail)++;
        continue;
      }
    (void) fprintf(stdout,"... pass.\n");
  }
  (void) fprintf(stdout,"  summary: %lu subtests; %lu passed; %lu failed.\n",
    test,test-(*fail),*fail);
  return(test);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                                             %
%                                                                             %
%                                                                             %
%  M a i n                                                                    %
%                                                                             %
%                                                                             %
%                                                                             %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/
int main(int argc,char **argv)
{
  char
    *option,
    *text;

  ExceptionInfo
    *exception;

  ImageInfo
    *image_info;

  MagickBooleanType
    regard_warnings,
    status;

  register long
    i;

  MagickCoreGenesis(*argv,MagickTrue);
  exception=AcquireExceptionInfo();
  regard_warnings=MagickFalse;
  for (i=1; i < (long) argc; i++)
  {
    option=argv[i];
    if ((strlen(option) == 1) || ((*option != '-') && (*option != '+')))
      continue;
    if (LocaleCompare("debug",option+1) == 0)
      (void) SetLogEventMask(argv[++i]);
    if (LocaleCompare("regard-warnings",option+1) == 0)
      regard_warnings=MagickTrue;
  }
  image_info=AcquireImageInfo();
  text=(char *) NULL;
  status=CompareImageCommand(image_info,argc,argv,&text,exception);
  if ((status == MagickFalse) || (exception->severity != UndefinedException))
    {
      if ((exception->severity < ErrorException) &&
          (regard_warnings == MagickFalse))
        status=MagickTrue;
      CatchException(exception);
    }
  if (text != (char *) NULL)
    {
      (void) fputs(text,stdout);
      (void) fputc('\n',stdout);
      text=DestroyString(text);
    }
  image_info=DestroyImageInfo(image_info);
  exception=DestroyExceptionInfo(exception);
  MagickCoreTerminus();
  return(status == MagickFalse ? 1 : 0);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                                             %
%                                                                             %
%                                                                             %
%  M a i n                                                                    %
%                                                                             %
%                                                                             %
%                                                                             %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/
int main(int argc,char **argv)
{
  char
    *option,
    *text;

  ExceptionInfo
    exception;

  ImageInfo
    *image_info;

  MagickBooleanType
    status;

  register long
    i;

  InitializeMagick(*argv);
  GetExceptionInfo(&exception);
  for (i=1; i < (long) argc; i++)
  {
    option=argv[i];
    if ((strlen(option) == 1) || ((*option != '-') && (*option != '+')))
      continue;
    if ((LocaleCompare("debug",option+1) == 0) && (i < (long) (argc-1)))
      (void) SetLogEventMask(argv[++i]);
    if (LocaleCompare("version",option+1) == 0)
      {
        (void) fprintf(stdout,"Version: %s\n",
          GetMagickVersion((unsigned long *) NULL));
        (void) fprintf(stdout,"Copyright: %s\n\n",GetMagickCopyright());
        exit(0);
      }
  }
  image_info=CloneImageInfo((ImageInfo *) NULL);
  text=(char *) NULL;
  status=IdentifyImageCommand(image_info,argc,argv,&text,&exception);
  if (exception.severity != UndefinedException)
    CatchException(&exception);
  if (text != (char *) NULL)
    {
      (void) fputs(text,stdout);
      (void) fputc('\n',stdout);
      text=(char *) RelinquishMagickMemory(text);
    }
  image_info=DestroyImageInfo(image_info);
  DestroyExceptionInfo(&exception);
  DestroyMagick();
  exit(!status);
  return(MagickFalse);
}
Exemple #16
0
Int ConsoleApplication::Run()
{
    auto xc = CatchException( [ this ] { return this->Main(); } );
    if ( xc )
    {
        TraceError( xc.TracingMessage() );

        std::cout << std::endl
                  << "Program caught an exception and exit abnormally." << std::endl;
        std::cin.get();
    }
    return xc.Result();
}
Image		*get_green_grayscale_image(Image *img)
{
  unsigned int	i = 0;
  unsigned int	j = 0;
  PixelPacket	*px_original;
  Image		*new_img;
  ExceptionInfo	exception;
  unsigned char *new_raw_image;

  GetExceptionInfo(&exception);

  if ((px_original = GetImagePixelsEx(img, 0, 0, img->columns, img->rows, &exception)) == NULL)
    {
      CatchException(&exception);
      return (NULL);
    }

  new_raw_image = malloc((img->rows * img->columns) * sizeof(*new_raw_image));

  while (i < img->rows)
    {
      j = 0;
      while (j < img->columns)
	{
	  new_raw_image[(img->columns * i) + j] = px_original[(img->columns * i) + j].green;
	  j++;
	}
      i++;
    }

  if ((new_img = ConstituteImage(img->columns, img->rows, "I", CharPixel, new_raw_image, &exception)) == NULL) {
    CatchException(&exception);
    return (NULL);
  }

  free(new_raw_image);
  return (new_img);
}
Image		*crop_image_from_path(char *path, RectangleInfo *portion)
{
  ImageInfo	*image_info;
  Image		*img;
  Image		*tmp;
  ExceptionInfo	exception;

  GetExceptionInfo(&exception);
  if ((image_info = CloneImageInfo((ImageInfo *)NULL)) == NULL) {
    CatchException(&exception);
    DestroyImageInfo(image_info);
    return (NULL);
  }

  strcpy(image_info->filename, path);

  if ((img = ReadImage(image_info, &exception)) == NULL)
    {
      CatchException(&exception);
      DestroyImageInfo(image_info);
      return (NULL);
    }

  tmp = img;

  if ((img = CropImage(img, portion, &exception)) == NULL) {
    CatchException(&exception);
    DestroyImage(tmp);
    DestroyImageInfo(image_info);
    return (NULL);
  }

  DestroyImage(tmp);
  DestroyImageInfo(image_info);
  return (img);
}
static unsigned int
ngx_http_graphicsmagick_convert(char **argv, size_t argc)
{
	// GraphicsMagick stuff
	ngx_uint_t				   i;
	char					  *option;
	ExceptionInfo			  exception;
	ImageInfo				  *image_info;
	MagickBool		   regard_warnings, status;
	
	// DO GraphicsMagick converting
	InitializeMagick((char *) NULL);

	GetExceptionInfo(&exception);
	regard_warnings = 0;
	for (i = 1; i < argc; i++) {
		option = argv[i];
		
		if ((ngx_strlen(option) == 1) || ((*option != '-') && (*option != '+'))) {
			continue;
		}
		if (LocaleCompare("debug", option + 1) == 0) {
			(void) SetLogEventMask(argv[++i]);
		}
		if (LocaleCompare("regard-warnings",option+1) == 0) {
			regard_warnings = MagickTrue;
		}
	}

	image_info = CloneImageInfo(0);
	status = ConvertImageCommand(image_info, argc, argv, NULL, &exception);
	
	if ((status == MagickFalse) || (exception.severity != UndefinedException)) {
		if ((exception.severity < ErrorException) && (regard_warnings == MagickFalse)) {
			status = MagickTrue;
		}
		CatchException(&exception);
	}
	
	DestroyImageInfo(image_info);
	DestroyExceptionInfo(&exception);

	return status;
}
Exemple #20
0
static
ERL_NIF_TERM exmagick_crop (ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[])
{
  Image* cropped_image;
  RectangleInfo rect;
  exm_resource_t *resource;

  EXM_INIT;
  ErlNifResourceType *type = (ErlNifResourceType *) enif_priv_data(env);

  if (0 == enif_get_resource(env, argv[0], type, (void **) &resource))
  { EXM_FAIL(ehandler, "invalid handle"); }

  if (resource->image == NULL)
  { EXM_FAIL(ehandler, "image not loaded"); }

  /* build rectangle */
  if (0 == enif_get_long(env, argv[1], &rect.x))
  { EXM_FAIL(ehandler, "x0: bad argument"); }

  if (0 == enif_get_long(env, argv[2], &rect.y))
  { EXM_FAIL(ehandler, "y0: bad argument"); }

  if (0 == enif_get_ulong(env, argv[3], &rect.width))
  { EXM_FAIL(ehandler, "width: bad argument"); }

  if (0 == enif_get_ulong(env, argv[4], &rect.height))
  { EXM_FAIL(ehandler, "height: bad argument"); }

  /* actually crops image */
  cropped_image = CropImage(resource->image, &rect, &resource->e_info);
  if (cropped_image == NULL)
  {
    CatchException(&resource->e_info);
    EXM_FAIL(ehandler, resource->e_info.reason);
  }
  DestroyImage(resource->image);
  resource->image = cropped_image;

  return(enif_make_tuple2(env, enif_make_atom(env, "ok"), argv[0]));

ehandler:
  return(enif_make_tuple2(env, enif_make_atom(env, "error"), exmagick_make_utf8str(env, errmsg)));
}
int   		dump_multi_image(Image *img, char *root_path, char *name, char *image_type)
{
    char		*final_path;
    ImageInfo	*image_info;
    ExceptionInfo	exception;
    
    GetExceptionInfo(&exception);
    if ((image_info = CloneImageInfo((ImageInfo *)NULL)) == NULL) {
        CatchException(&exception);
        DestroyImageInfo(image_info);
        return -1;
    }
    
    asprintf(&final_path, "%s/%s.%s", root_path, name, image_type);
    strcpy(img->filename, final_path);
    WriteImage(image_info, img);
    free(final_path);
    return (0);
}
Exemple #22
0
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                                             %
%                                                                             %
%                                                                             %
+   C L I C a t c h E x c e p t i o n                                         %
%                                                                             %
%                                                                             %
%                                                                             %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  CLICatchException() will report exceptions, either just non-fatal warnings
%  only, or all errors, according to 'all_execeptions' boolean argument.
%
%  The function returns true if errors are fatal, in which case the caller
%  should abort and re-call with an 'all_exceptions' argument of true before
%  quitting.
%
%  The cut-off level between fatal and non-fatal may be controlled by options
%  (FUTURE), but defaults to 'Error' exceptions.
%
%  The format of the CLICatchException method is:
%
%    MagickBooleanType CLICatchException(MagickCLI *cli_wand,
%              const MagickBooleanType all_exceptions );
%
%  Arguments are
%
%    o cli_wand:   The Wand CLI that holds the exception Information
%
%    o all_exceptions:   Report all exceptions, including the fatal one
%
*/
WandExport MagickBooleanType CLICatchException(MagickCLI *cli_wand,
     const MagickBooleanType all_exceptions )
{
  MagickBooleanType
    status;
  assert(cli_wand != (MagickCLI *) NULL);
  assert(cli_wand->signature == WandSignature);
  assert(cli_wand->wand.signature == WandSignature);
  if (IfMagickTrue(cli_wand->wand.debug))
    (void) LogMagickEvent(WandEvent,GetMagickModule(),"%s",cli_wand->wand.name);

  // FUTURE: '-regard_warning' should make this more sensitive.
  // Note pipelined options may like more control over this level

  status = IsMagickTrue(cli_wand->wand.exception->severity > ErrorException);

  if ( IfMagickFalse(status) || IfMagickTrue(all_exceptions) )
    CatchException(cli_wand->wand.exception); /* output and clear exceptions */

  return(status);
}
bool ScImgDataLoader_GMagick::readRGB(Image *input, QImage *output, int width, int height)
{
	bool hasAlpha = input->matte;

	ExceptionInfo exception;
	GetExceptionInfo(&exception);
	const PixelPacket *pixels = AcquireImagePixels(input, 0, 0, width, height, &exception);
	if (exception.severity != UndefinedException)
		CatchException(&exception);
	if (!pixels) {
		qCritical() << QObject::tr("Could not get pixel data!");
		return false;
	}

	unsigned char *buffer = output->bits();
	if (!buffer) {
		qCritical() << QObject::tr("Could not allocate output buffer!");
		return false;
	}

	QRgb *s = (QRgb*)(output->scanLine(0));
	int i;
	for (i = 0; i < width*height; i++)
	{
		unsigned char b = ScaleQuantumToChar(pixels[i].blue);
		unsigned char g = ScaleQuantumToChar(pixels[i].green);
		unsigned char r = ScaleQuantumToChar(pixels[i].red);
		unsigned char a;
		if (hasAlpha)
			a = 255 - ScaleQuantumToChar(pixels[i].opacity);
		else
			a = 255;
		*s = qRgba(r, g, b, a);
		s++;
	}
	return true;
}
Exemple #24
0
static
ERL_NIF_TERM exmagick_image_thumb (ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[])
{
  long width, height;
  Image* thumb;
  exm_resource_t *resource;

  EXM_INIT;
  ErlNifResourceType *type = (ErlNifResourceType *) enif_priv_data(env);

  if (0 == enif_get_resource(env, argv[0], type, (void **) &resource))
  { EXM_FAIL(ehandler, "invalid handle"); }

  if (resource->image == NULL)
  { EXM_FAIL(ehandler, "image not loaded"); }

  if (0 == enif_get_long(env, argv[1], &width))
  { EXM_FAIL(ehandler, "width: bad argument"); }

  if (0 == enif_get_long(env, argv[2], &height))
  { EXM_FAIL(ehandler, "height: bad argument"); }

  thumb = ThumbnailImage(resource->image, width, height, &resource->e_info);
  if (thumb == NULL)
  {
    CatchException(&resource->e_info);
    EXM_FAIL(ehandler, resource->e_info.reason);
  }
  DestroyImage(resource->image);
  resource->image = thumb;

  return(enif_make_tuple2(env, enif_make_atom(env, "ok"), argv[0]));

ehandler:
  return(enif_make_tuple2(env, enif_make_atom(env, "error"), exmagick_make_utf8str(env, errmsg)));
}
static int load_images(LogoPrivateData *pd)
{
    Image         *timg;
    Image         *nimg;

    pd->images = GetFirstImageInList(pd->magick.image);
    nimg = NewImageList();

    while (pd->images != (Image *)NULL) {
        if (pd->flip) {
            timg = FlipImage(pd->images, 
                             &pd->magick.exception_info);
            if (timg == NULL) {
                CatchException(&pd->magick.exception_info);
                return TC_ERROR;
            }
            AppendImageToList(&nimg, timg);
        }

        pd->images = GetNextImageInList(pd->images);
        pd->nr_of_images++;
    }

    // check for memleaks;
    //DestroyImageList(image);
    if (pd->flip) {
        /* DANGEROUS!!! */
        pd->magick.image = nimg;
    }

    /* for running through image sequence */
    /* DANGEROUS!!! */
    pd->images = pd->magick.image;

    return TC_OK;
}
Exemple #26
0
WandExport MagickBooleanType ConjureImageCommand(ImageInfo *image_info,
  int argc,char **argv,char **wand_unused(metadata),ExceptionInfo *exception)
{
#define DestroyConjure() \
{ \
  image=DestroyImageList(image); \
  for (i=0; i < (ssize_t) argc; i++) \
    argv[i]=DestroyString(argv[i]); \
  argv=(char **) RelinquishMagickMemory(argv); \
}
#define ThrowConjureException(asperity,tag,option) \
{ \
  (void) ThrowMagickException(exception,GetMagickModule(),asperity,tag,"'%s'", \
     option); \
  DestroyConjure(); \
  return(MagickFalse); \
}
#define ThrowConjureInvalidArgumentException(option,argument) \
{ \
  (void) ThrowMagickException(exception,GetMagickModule(),OptionError, \
    "InvalidArgument","'%s': %s",option,argument); \
  DestroyConjure(); \
  return(MagickFalse); \
}

  char
    filename[MaxTextExtent],
    *option;

  Image
    *image;

  MagickStatusType
    status;

  register ssize_t
    i;

  ssize_t
    number_images;

  /*
    Set defaults.
  */
  assert(image_info != (ImageInfo *) NULL);
  assert(image_info->signature == MagickSignature);
  if (image_info->debug != MagickFalse)
    (void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
  assert(exception != (ExceptionInfo *) NULL);
  if (argc < 2)
    return(ConjureUsage());
  image=NewImageList();
  number_images=0;
  option=(char *) NULL;
  /*
    Conjure an image.
  */
  ReadCommandlLine(argc,&argv);
  status=ExpandFilenames(&argc,&argv);
  if (status == MagickFalse)
    ThrowConjureException(ResourceLimitError,"MemoryAllocationFailed",
      GetExceptionMessage(errno));
  for (i=1; i < (ssize_t) argc; i++)
  {
    option=argv[i];
    if (IsCommandOption(option) != MagickFalse)
      {
        if (LocaleCompare("concurrent",option+1) == 0)
          break;
        if (LocaleCompare("debug",option+1) == 0)
          {
            ssize_t
              event;

            if (*option == '+')
              break;
            i++;
            if (i == (ssize_t) argc)
              ThrowConjureException(OptionError,"MissingArgument",option);
            event=ParseCommandOption(MagickLogEventOptions,MagickFalse,argv[i]);
            if (event < 0)
              ThrowConjureException(OptionError,"UnrecognizedEventType",
                argv[i]);
            (void) SetLogEventMask(argv[i]);
            continue;
          }
        if (LocaleCompare("duration",option+1) == 0)
          {
            if (*option == '+')
              break;
            i++;
            if (i == (ssize_t) (argc-1))
              ThrowConjureException(OptionError,"MissingArgument",option);
            if (IsGeometry(argv[i]) == MagickFalse)
              ThrowConjureInvalidArgumentException(option,argv[i]);
            continue;
          }
        if ((LocaleCompare("help",option+1) == 0) ||
            (LocaleCompare("-help",option+1) == 0))
          {
            if (*option == '-')
              return(ConjureUsage());
            continue;
          }
        if (LocaleCompare("log",option+1) == 0)
          {
            if (*option == '-')
              {
                i++;
                if (i == (ssize_t) argc)
                  ThrowConjureException(OptionError,"MissingLogFormat",option);
                (void) SetLogFormat(argv[i]);
              }
            continue;
          }
        if (LocaleCompare("monitor",option+1) == 0)
          continue;
        if (LocaleCompare("quiet",option+1) == 0)
          continue;
        if (LocaleCompare("regard-warnings",option+1) == 0)
          break;
        if (LocaleCompare("seed",option+1) == 0)
          {
            if (*option == '+')
              break;
            i++;
            if (i == (ssize_t) (argc-1))
              ThrowConjureException(OptionError,"MissingArgument",option);
            if (IsGeometry(argv[i]) == MagickFalse)
              ThrowConjureInvalidArgumentException(option,argv[i]);
            break;
          }
        if (LocaleCompare("verbose",option+1) == 0)
          {
            image_info->verbose=(*option == '-') ? MagickTrue : MagickFalse;
            continue;
          }
        if ((LocaleCompare("version",option+1) == 0) ||
            (LocaleCompare("-version",option+1) == 0))
          {
            (void) FormatLocaleFile(stdout,"Version: %s\n",
              GetMagickVersion((size_t *) NULL));
            (void) FormatLocaleFile(stdout,"Copyright: %s\n",
              GetMagickCopyright());
            (void) FormatLocaleFile(stdout,"Features: %s\n\n",
              GetMagickFeatures());
            return(MagickFalse);
          }
        /*
          Persist key/value pair.
        */
        (void) DeleteImageOption(image_info,option+1);
        status=SetImageOption(image_info,option+1,argv[i+1]);
        if (status == MagickFalse)
          ThrowConjureException(ImageError,"UnableToPersistKey",option);
        i++;
        continue;
      }
    /*
      Interpret MSL script.
    */
    (void) DeleteImageOption(image_info,"filename");
    status=SetImageOption(image_info,"filename",argv[i]);
    if (status == MagickFalse)
      ThrowConjureException(ImageError,"UnableToPersistKey",argv[i]);
    (void) FormatLocaleString(filename,MaxTextExtent,"msl:%s",argv[i]);
    image=ReadImages(image_info,filename,exception);
    CatchException(exception);
    if (image != (Image *) NULL)
      image=DestroyImageList(image);
    status=image != (Image *) NULL ? MagickTrue : MagickFalse;
    number_images++;
  }
  if (i != (ssize_t) argc)
    ThrowConjureException(OptionError,"MissingAnImageFilename",argv[i]);
  if (number_images == 0)
    ThrowConjureException(OptionError,"MissingAnImageFilename",argv[argc-1]);
  if (image != (Image *) NULL)
    image=DestroyImageList(image);
  for (i=0; i < (ssize_t) argc; i++)
    argv[i]=DestroyString(argv[i]);
  argv=(char **) RelinquishMagickMemory(argv);
  return(status != 0 ? MagickTrue : MagickFalse);
}
Exemple #27
0
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                                             %
%                                                                             %
%                                                                             %
%   R e a d X T R N I m a g e                                                 %
%                                                                             %
%                                                                             %
%                                                                             %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  ReadXTRNImage() reads a XTRN image file and returns it.  It
%  allocates the memory necessary for the new Image structure and returns a
%  pointer to the new image.
%
%  The format of the ReadXTRNImage method is:
%
%      Image *ReadXTRNImage(const ImageInfo *image_info,
%        ExceptionInfo *exception)
%
%  A description of each parameter follows:
%
%    o image_info: Specifies a pointer to an ImageInfo structure.
%
%    o exception: return any errors or warnings in this structure.
%
*/
static Image *ReadXTRNImage(const ImageInfo *image_info,
  ExceptionInfo *exception)
{
  Image
    *image;

  ImageInfo
    *clone_info;

  void
    *param1,
    *param2,
    *param3;

  param1 = param2 = param3 = (void *) NULL;
  image = (Image *) NULL;
  clone_info=CloneImageInfo(image_info);
  if (clone_info->filename == NULL)
    {
      clone_info=DestroyImageInfo(clone_info);
      ThrowReaderException(FileOpenWarning,"No filename specified");
    }
  if (LocaleCompare(image_info->magick,"XTRNFILE") == 0)
    {
      image=ReadImage(clone_info,exception);
      CatchException(exception);
    }
  else if (LocaleCompare(image_info->magick,"XTRNIMAGE") == 0)
    {
      Image
        **image_ptr;

#ifdef ALL_IMAGEINFO
      ImageInfo
        **image_info_ptr;
#endif

      (void) sscanf(clone_info->filename,"%lx,%lx",&param1,&param2);
      image_ptr=(Image **) param2;
      if (*image_ptr != (Image *)NULL)
        image=CloneImage(*image_ptr,0,0,MagickFalse,&(*image_ptr)->exception);
#ifdef ALL_IMAGEINFO
      image_info_ptr=(ImageInfo **) param1;
      if (*image_info_ptr != (ImageInfo *)NULL)
        image_info=*image_info_ptr;
#endif
    }
  else if (LocaleCompare(image_info->magick,"XTRNBLOB") == 0)
    {
      char
        **blob_data;

      size_t
        *blob_length;

      char
        filename[MaxTextExtent];

      (void) sscanf(clone_info->filename,"%lx,%lx,%s",&param1,&param2,&filename);
      blob_data=(char **) param1;
      blob_length=(size_t *) param2;
      image=BlobToImage(clone_info,*blob_data,*blob_length,exception);
      CatchException(exception);
    }
  else if (LocaleCompare(image_info->magick,"XTRNSTREAM") == 0)
    {
#ifdef IMPLEMENT_THIS
      MagickBooleanType
        status;
#endif

      char
        filename[MaxTextExtent];

      size_t
        (*fifo)(const Image *,const void *,const size_t);

      (void) sscanf(clone_info->filename,"%lx,%lx,%s",&param1,&param2,&filename);
      fifo=(size_t (*)(const Image *,const void *,const size_t)) param1;
      clone_info->client_data=param2;
#ifdef IMPLEMENT_THIS
      status=ReadStream(clone_info,fifo,exception);
      CatchException(exception);
#endif
    }
  else if (LocaleCompare(image_info->magick,"XTRNARRAY") == 0)
    {
      SAFEARRAY
        *pSafeArray;

      char
        *blob_data;

      size_t
        blob_length;

                  long
        lBoundl,
        lBoundu;

      HRESULT
        hr;

      char
        filename[MaxTextExtent];

      filename[0] = '\0';
      (void) sscanf(clone_info->filename,"%lx,%s",&param1,&filename);
            hr = S_OK;
      pSafeArray = (SAFEARRAY *) param1;
      if (pSafeArray)
        {
                      hr = SafeArrayGetLBound(pSafeArray, 1, &lBoundl);
          if (SUCCEEDED(hr))
                        hr = SafeArrayGetUBound(pSafeArray, 1, &lBoundu);
          if (SUCCEEDED(hr))
            {
                          blob_length = lBoundu - lBoundl + 1;
              hr = SafeArrayAccessData(pSafeArray, (void**)&blob_data);
                    if(SUCCEEDED(hr))
                {
                  if (filename[0] != '\0')
                    {
                      (void) CopyMagickString(clone_info->filename,filename,
                        MaxTextExtent);
                      (void) CopyMagickString(clone_info->magick,filename,
                        MaxTextExtent);
                    }
                  else
                    {
                      *clone_info->magick = '\0';
                      clone_info->filename[0] = '\0';
                    }
                  image=BlobToImage(clone_info,blob_data,blob_length,exception);
                  hr = SafeArrayUnaccessData(pSafeArray);
                  CatchException(exception);
                }
            }
        }
    }
  else if (LocaleCompare(image_info->magick,"XTRNBSTR") == 0)
    {
      BSTR
        bstr;

      char
        *blob_data;

      size_t
        blob_length;

      HRESULT
        hr;

      char
        filename[MaxTextExtent];

      filename[0] = '\0';
      (void) sscanf(clone_info->filename,"%lx,%s",&param1,&filename);
      hr = S_OK;
      bstr = (BSTR) param1;
      blob_length = SysStringLen(bstr) * 2;
      blob_data = (char *)bstr;
      if ((blob_data != (char *)NULL) && (blob_length>0))
        {
          if (filename[0] != '\0')
            {
              (void) CopyMagickString(clone_info->filename,filename,
                MaxTextExtent);
              (void) CopyMagickString(clone_info->magick,filename,
                MaxTextExtent);
            }
          else
            {
              *clone_info->magick = '\0';
              clone_info->filename[0] = '\0';
            }
          image=BlobToImage(clone_info,blob_data,blob_length,exception);
          CatchException(exception);
        }
    }
  clone_info=DestroyImageInfo(clone_info);
  return(image);
}
Exemple #28
0
std::string
imageproc::ChangeImage(const std::string & inPath,
                       const std::string & tmpDir,
                       Type outputFormat,
                       const bp::List & transformations,
                       int quality,
                       unsigned int & x, unsigned int & y, 
                       unsigned int & orig_x, unsigned int & orig_y, 
                       std::string & oError)
{
    ExceptionInfo exception;
    Image *images;
    ImageInfo *image_info;

    orig_x = orig_y = x = y = 0;
    
    GetExceptionInfo(&exception);
    image_info = CloneImageInfo((ImageInfo *) NULL);

    // first we read the image
    if (exception.severity != UndefinedException)
    {
		if (exception.reason)
            g_bpCoreFunctions->log(BP_ERROR, "after: %s\n",
                                   exception.reason);
		if (exception.description)
            g_bpCoreFunctions->log(BP_ERROR, "after: %s\n",
                                   exception.description);
		CatchException(&exception);
    }


	(void) strcpy(image_info->filename, inPath.c_str());
    images = IP_ReadImageFile(image_info, inPath, &exception);
    
    if (exception.severity != UndefinedException)
    {
		if (exception.reason)
            g_bpCoreFunctions->log(BP_ERROR, "after: %s\n",
                                   exception.reason);
		if (exception.description)
            g_bpCoreFunctions->log(BP_ERROR, "after: %s\n",
                                   exception.description);
		CatchException(&exception);
    }
    
    if (!images)
    {
        oError.append("couldn't read image");
        DestroyImageInfo(image_info);
        image_info = NULL;
        DestroyExceptionInfo(&exception);
        return std::string();
    }

	g_bpCoreFunctions->log(
        BP_INFO, "Image contains %lu frames, type: %s\n",
        GetImageListLength(images),
        images->magick);

    // set quality
    if (quality > 100) quality = 100;
    if (quality < 0) quality = 0;
    image_info->quality = quality;

    g_bpCoreFunctions->log(
        BP_INFO, "Quality set to %d (0-100, worst-best)", quality);

    // execute 'actions' 
    images = runTransformations(images, transformations, quality, oError);

    // was all that successful?
    if (!images)
    {
        DestroyImageInfo(image_info);
        image_info = NULL;
        DestroyExceptionInfo(&exception);
        return std::string();
    } 

    // set the output size
    orig_x = images->magick_columns;
    orig_y = images->magick_rows;
    x = images->columns;
    y = images->rows;

    // let's set the output format correctly (default to input format)
    std::string name;
    if (outputFormat == UNKNOWN) name.append(ft::basename(inPath));
    else {
        name.append("img.");
        name.append(typeToExt(outputFormat));
        (void) sprintf(images->magick, outputFormat);
        g_bpCoreFunctions->log(BP_INFO, "Output to format: %s", outputFormat);
    }
    
    // Now let's go directly from blob to file.  We bypass
    // GM to-file functions so that we can handle wide filenames
    // safely on win32 systems.  A superior solution would
    // be to use GM stream facilities (if they exist)
    
    // upon success, will hold path to output file and will be returned to
    // client
    std::string rv;
    
    {
        size_t l = 0;
        void * blob = NULL;
        blob = ImageToBlob( image_info, images, &l, &exception );

        if (exception.severity != UndefinedException)
        {
            oError.append("ImageToBlob failed.");
            CatchException(&exception);
        }
        else
        {
            g_bpCoreFunctions->log(BP_INFO, "Writing %lu bytes to %s",
                                   l, name.c_str());

            if (!ft::mkdir(tmpDir, false)) {
                oError.append("Couldn't create temp dir");
            } else {
                std::string outpath = ft::getPath(tmpDir, name);
                FILE * f = ft::fopen_binary_write(outpath);
                if (f == NULL) { 
                    g_bpCoreFunctions->log(
                        BP_ERROR, "Couldn't open '%s' for writing!",
                        outpath.c_str());
                    oError.append("Error saving output image");
                } else {
                    size_t wt;
                    wt = fwrite(blob, sizeof(char), l, f);
                    fclose(f);

                    if (wt != l) {
                        g_bpCoreFunctions->log(
                            BP_ERROR,
                            "Partial write (%lu/%lu) when writing resultant "
                            "image '%s'",
                            wt, l, outpath.c_str());
                        oError.append("Error saving output image");
                    } else {
                        // success!
                        rv = outpath;
                    }
                }
            }
        }
    }
    
    DestroyImage(images);
    DestroyImageInfo(image_info);
    image_info = NULL;
    DestroyExceptionInfo(&exception);

    return rv;
}
Exemple #29
0
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                                             %
%                                                                             %
%                                                                             %
%   R e a d V I D I m a g e                                                   %
%                                                                             %
%                                                                             %
%                                                                             %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  ReadVIDImage reads one of more images and creates a Visual Image
%  Directory file.  It allocates the memory necessary for the new Image
%  structure and returns a pointer to the new image.
%
%  The format of the ReadVIDImage method is:
%
%      Image *ReadVIDImage(const ImageInfo *image_info,ExceptionInfo *exception)
%
%  A description of each parameter follows:
%
%    o image_info: the image info.
%
%    o exception: return any errors or warnings in this structure.
%
*/
static Image *ReadVIDImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
#define ClientName  "montage"

  char
    **filelist,
    *label;

  Image
    *image,
    *images,
    *montage_image,
    *next_image,
    *thumbnail_image;

  ImageInfo
    *read_info;

  int
    number_files;

  MagickBooleanType
    status;

  MontageInfo
    *montage_info;

  RectangleInfo
    geometry;

  register ssize_t
    i;

  /*
    Expand the filename.
  */
  assert(image_info != (const ImageInfo *) NULL);
  assert(image_info->signature == MagickSignature);
  if (image_info->debug != MagickFalse)
    (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
      image_info->filename);
  assert(exception != (ExceptionInfo *) NULL);
  assert(exception->signature == MagickSignature);
  image=AcquireImage(image_info);
  filelist=(char **) AcquireAlignedMemory(1,sizeof(*filelist));
  if (filelist == (char **) NULL)
    ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
  filelist[0]=ConstantString(image_info->filename);
  number_files=1;
  status=ExpandFilenames(&number_files,&filelist);
  if ((status == MagickFalse) || (number_files == 0))
    ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
  image=DestroyImage(image);
  /*
    Read each image and convert them to a tile.
  */
  images=NewImageList();
  read_info=CloneImageInfo(image_info);
  SetImageInfoBlob(read_info,(void *) NULL,0);
  (void) SetImageInfoProgressMonitor(read_info,(MagickProgressMonitor) NULL,
    (void *) NULL);
  if (read_info->size == (char *) NULL)
    (void) CloneString(&read_info->size,DefaultTileGeometry);
  for (i=0; i < (ssize_t) number_files; i++)
  {
    if (image_info->debug != MagickFalse)
      (void) LogMagickEvent(CoderEvent,GetMagickModule(),"name: %s",
        filelist[i]);
    (void) CopyMagickString(read_info->filename,filelist[i],MaxTextExtent);
    filelist[i]=DestroyString(filelist[i]);
    *read_info->magick='\0';
    next_image=ReadImage(read_info,exception);
    CatchException(exception);
    if (next_image == (Image *) NULL)
      break;
    label=InterpretImageProperties(image_info,next_image,DefaultTileLabel);
    (void) SetImageProperty(next_image,"label",label);
    label=DestroyString(label);
    if (image_info->debug != MagickFalse)
      (void) LogMagickEvent(CoderEvent,GetMagickModule(),
        "geometry: %.20gx%.20g",(double) next_image->columns,(double)
        next_image->rows);
    SetGeometry(next_image,&geometry);
    (void) ParseMetaGeometry(read_info->size,&geometry.x,&geometry.y,
      &geometry.width,&geometry.height);
    thumbnail_image=ThumbnailImage(next_image,geometry.width,geometry.height,
      exception);
    if (thumbnail_image != (Image *) NULL)
      {
        next_image=DestroyImage(next_image);
        next_image=thumbnail_image;
      }
    if (image_info->debug != MagickFalse)
      (void) LogMagickEvent(CoderEvent,GetMagickModule(),
        "thumbnail geometry: %.20gx%.20g",(double) next_image->columns,(double)
        next_image->rows);
    AppendImageToList(&images,next_image);
    status=SetImageProgress(images,LoadImagesTag,i,number_files);
    if (status == MagickFalse)
      break;
  }
  read_info=DestroyImageInfo(read_info);
  filelist=(char **) RelinquishMagickMemory(filelist);
  if (images == (Image *) NULL)
    ThrowReaderException(CorruptImageError,
      "ImageFileDoesNotContainAnyImageData");
  /*
    Create the visual image directory.
  */
  montage_info=CloneMontageInfo(image_info,(MontageInfo *) NULL);
  if (image_info->debug != MagickFalse)
    (void) LogMagickEvent(CoderEvent,GetMagickModule(),"creating montage");
  montage_image=MontageImageList(image_info,montage_info,
    GetFirstImageInList(images),exception);
  montage_info=DestroyMontageInfo(montage_info);
  images=DestroyImageList(images);
  return(montage_image);
}
Exemple #30
0
dt_imageio_retval_t
dt_imageio_open_gm(
  dt_image_t *img,
  const char *filename,
  dt_mipmap_cache_allocator_t a)
{
  int err = DT_IMAGEIO_FILE_CORRUPTED;
  float *buf = NULL;
  ExceptionInfo exception;
  Image *image = NULL;
  ImageInfo *image_info = NULL;
  uint32_t width, height, orientation;

  if(!_supported_image(filename)) return DT_IMAGEIO_FILE_CORRUPTED;

  if(!img->exif_inited)
    (void) dt_exif_read(img, filename);

  GetExceptionInfo(&exception);
  image_info=CloneImageInfo((ImageInfo *) NULL);

  g_strlcpy(image_info->filename,filename,sizeof(image_info->filename));

  image=ReadImage(image_info,&exception);
  if (exception.severity != UndefinedException)
    CatchException(&exception);
  if (!image)
  {
    fprintf(stderr, "[GraphicsMagick_open] image `%s' not found\n", img->filename);
    err = DT_IMAGEIO_FILE_NOT_FOUND;
    goto error;
  }

  width = image->columns;
  height = image->rows;
  orientation = image->orientation;

  if(orientation & 4)
  {
    img->width = height;
    img->height = width;
  }
  else
  {
    img->width = width;
    img->height = height;
  }

  img->bpp = 4*sizeof(float);

  float *mipbuf = (float *)dt_mipmap_cache_alloc(img, DT_MIPMAP_FULL, a);
  if(!mipbuf)
  {
    fprintf(stderr, "[GraphicsMagick_open] could not alloc full buffer for image `%s'\n", img->filename);
    err = DT_IMAGEIO_CACHE_FULL;
    goto error;
  }

  buf = (float *)dt_alloc_align(16, width*img->bpp);
  if(!buf) goto error;

  const int ht2 = orientation & 4 ? img->width  : img->height; // pretend unrotated, rotate in write_pos
  const int wd2 = orientation & 4 ? img->height : img->width;

  for (uint32_t row = 0; row < height; row++)
  {
    int ret = DispatchImage(image, 0, row, width, 1, "RGBP", FloatPixel, (void *)buf, &exception);
    if (exception.severity != UndefinedException)
      CatchException(&exception);
    if(ret != MagickPass)
    {
      fprintf(stderr, "[GraphicsMagick_open] error reading image `%s'\n", img->filename);
      err = DT_IMAGEIO_FILE_CORRUPTED;
      goto error;
    }

    for(uint32_t i=0; i<width; i++)
      for(int k=0; k<4; k++) mipbuf[4*dt_imageio_write_pos(i, row, wd2, ht2, wd2, ht2, orientation) + k] = buf[4*i + k];
  }

  if(buf) dt_free_align(buf);
  if(image) DestroyImage(image);
  if(image_info) DestroyImageInfo(image_info);
  DestroyExceptionInfo(&exception);

  img->filters = 0;
  img->flags &= ~DT_IMAGE_RAW;
  img->flags &= ~DT_IMAGE_HDR;
  img->flags |= DT_IMAGE_LDR;

  return DT_IMAGEIO_OK;

error:
  if(buf) dt_free_align(buf);
  if(image) DestroyImage(image);
  if(image_info) DestroyImageInfo(image_info);
  DestroyExceptionInfo(&exception);
  return err;
}