使用GAE Image API进行图像转换

xyb*_*rek 2 java google-app-engine image image-processing

我试图了解如何处理GAE Image api,自动将图像格式转换为JPEG.

这是我的代码:

byte[] oldImageData = model.getImage();
Image oldImage = ImagesServiceFactory.makeImage(oldImageData);
LOG.info("Image format - " + oldImage.getFormat().toString());
model.setImage(oldImage.getImageData()); // byte array must be JPEG
Run Code Online (Sandbox Code Playgroud)

oldImageData这里的字节数组可以是JPEG或PNG图像的字节数组,或者最坏的情况不是图像.

  • 如果字节数组不是图像数据,我的应用程序需要捕获的异常是什么?
  • 如果字节数组是图像但我的应用程序不知道确切的类型,应该做什么,以便GAE图像服务将自动将其转换为JPEG.

最后,我需要做的是确保它oldImageDataJPEG图像的字节数组.

Pet*_*ego 6

ImagesService imagesService = ImagesServiceFactory.getImagesService();
Image oldImage = ImagesServiceFactory.makeImage(oldImageData);

// this throws an exception if data is not image or unsupported format
// you can wrap this in try..catch and act accordingly 
oldImage.getFormat();

// this is a dummy transform that does nothing
Transform transform = ImagesServiceFactory.makeCrop(0.0, 0.0, 1.0, 1.0);

// setting the output to JPEG
OutputSettings outputSettings = new OutputSettings(ImagesService.OutputEncoding.JPEG);
outputSettings.setQuality(100);

// apply dummy transform and output settings
Image newImage = imagesService.applyTransform(transform, oldImage, outputSettings);

byte[] newImageData = newImage.getImageData();
Run Code Online (Sandbox Code Playgroud)