我使用java代码压缩图像。有时我会得到错误颜色的图像。我不明白为什么它的行为是不一致的。
从网址下载的图片
public void imageDownload() {
String key = (String) map.get("key");
String url = (String) map.get("url");
**String imagePath = java.util.UUID.randomUUID() + ".jpg";
String compressedImage = Constant.COMPRESSED + imagePath;**
try {
URL url = new URL(url);
InputStream is = url.openStream();
// Stream to the destionation file
FileOutputStream fos = new FileOutputStream(imagePath);
// Read bytes from URL to the local file
byte[] buffer = new byte[4096];
int bytesRead = 0;
while ((bytesRead = is.read(buffer)) != -1)
fos.write(buffer, 0, bytesRead);
// Close destination stream
fos.close();
// Close URL stream
is.close();
compressFile(imagePath, compressedImage, key);
} catch (Exception exception) {
log.debug("Exception occured while downloading images..." + exception.getLocalizedMessage());
}
}
}
图片压缩代码
private void compressFile(final String inputFilePath, final String outputFilePath,final String fileKey) {
log.debug("Image file name::" + outputFilePath);
log.debug("Image key is::" + fileKey);
final String outputImagePath = tempFilePath + outputFilePath;
final File inputFile = new File(inputFilePath);
float quality = FileUpload.getQuality(inputFile);
log.debug("Image size for url is::" + inputFile.length() + "quality constent::" + quality);
final File outputFile = new File(outputImagePath);
boolean s3Uploaded = true;
if (quality != 0.0f) {
final boolean isCompressed = FileUpload.fileCompress(inputFile, outputFile, quality);
}
}
压缩代码
public static boolean fileCompress(File inputFilePath, File outputFilePath, float quality) {
log.debug("File compress with path::" + inputFilePath + "output file path" + outputFilePath);
boolean isCompressed = false;
OutputStream os = null;
ImageOutputStream ios = null;
ImageWriter writer = null;
try {
BufferedImage image = ImageIO.read(inputFilePath);
os = new FileOutputStream(outputFilePath);
Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName("jpg");
writer = (ImageWriter) writers.next();
ios = ImageIO.createImageOutputStream(os);
writer.setOutput(ios);
ImageWriteParam param = writer.getDefaultWriteParam();
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
param.setCompressionQuality(quality);
writer.write(null, new IIOImage(image, null, null), param);
os.close();
ios.close();
writer.dispose();
isCompressed = true;
} catch (Exception exception) {
log.error("File could not compress due to " + exception.getCause());
isCompressed= false;
}
return isCompressed;
}
获得质量参数
public static float getQuality(File input) {
long size = input.length();
log.debug("getting quality constant on the basis of image size: " + size);
if (size > 768000) {
return 0.3f;
}
if (size > 512000 && size <= 768000) {
return 0.6f;
}
if (size > 256000 && size <= 512000) {
return 0.7f;
}
if (size > 51200) {
return 0.9f;
}
return 0.0f;
}
由于