- /* Allocate image for conversion */
- int need_scale = io->cols != rd->image->columns || io->rows != rd->image->rows;
- int need_destroy = need_scale || !io->pool;
- struct image *img = need_scale ?
- image_new(io->thread, rd->image->columns, rd->image->rows, io->flags & IMAGE_CHANNELS_FORMAT, NULL) :
- image_new(io->thread, io->cols, io->rows, io->flags, io->pool);
- if (unlikely(!img))
- goto err;
+ /* Prepare the image */
+ struct image_io_read_data_internals rdi;
+ uns read_flags = io->flags;
+ uns cs = read_flags & IMAGE_COLOR_SPACE;
+ if (cs != COLOR_SPACE_GRAYSCALE && cs != COLOR_SPACE_RGB)
+ read_flags = (read_flags & ~IMAGE_COLOR_SPACE & IMAGE_PIXEL_FORMAT) | COLOR_SPACE_RGB;
+ if ((read_flags & IMAGE_IO_USE_BACKGROUND) && !(read_flags & IMAGE_ALPHA))
+ read_flags = (read_flags & IMAGE_CHANNELS_FORMAT) | IMAGE_ALPHA;
+ if (unlikely(!image_io_read_data_prepare(&rdi, io, rd->image->columns, rd->image->rows, read_flags)))
+ {
+ libmagick_destroy_read_data(rd);
+ return 0;
+ }