मैं उच्चतम गुणवत्ता संरक्षित पहलू अनुपात के साथ आकार परिवर्तन चाहते थे। कुछ चीजों की कोशिश की और कई प्रविष्टियों को पढ़ा। दो दिन खो दिया और अंत में मैं सादे जावा विधि के साथ सबसे अच्छा परिणाम मिला (ImageMagick भी कोशिश की और जावा छवि स्केलिंग पुस्तकालयों):
public static boolean resizeUsingJavaAlgo(String source, File dest, int width, int height) throws IOException {
BufferedImage sourceImage = ImageIO.read(new FileInputStream(source));
double ratio = (double) sourceImage.getWidth()/sourceImage.getHeight();
if (width < 1) {
width = (int) (height * ratio + 0.4);
} else if (height < 1) {
height = (int) (width /ratio + 0.4);
}
Image scaled = sourceImage.getScaledInstance(width, height, Image.SCALE_AREA_AVERAGING);
BufferedImage bufferedScaled = new BufferedImage(scaled.getWidth(null), scaled.getHeight(null), BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = bufferedScaled.createGraphics();
g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
g2d.drawImage(scaled, 0, 0, width, height, null);
dest.createNewFile();
writeJpeg(bufferedScaled, dest.getCanonicalPath(), 1.0f);
return true;
}
/**
* Write a JPEG file setting the compression quality.
*
* @param image a BufferedImage to be saved
* @param destFile destination file (absolute or relative path)
* @param quality a float between 0 and 1, where 1 means uncompressed.
* @throws IOException in case of problems writing the file
*/
private static void writeJpeg(BufferedImage image, String destFile, float quality)
throws IOException {
ImageWriter writer = null;
FileImageOutputStream output = null;
try {
writer = ImageIO.getImageWritersByFormatName("jpeg").next();
ImageWriteParam param = writer.getDefaultWriteParam();
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
param.setCompressionQuality(quality);
output = new FileImageOutputStream(new File(destFile));
writer.setOutput(output);
IIOImage iioImage = new IIOImage(image, null, null);
writer.write(null, iioImage, param);
} catch (IOException ex) {
throw ex;
} finally {
if (writer != null) {
writer.dispose();
}
if (output != null) {
output.close();
}
}
}
स्रोत
2013-05-31 14:16:09
मैं बाहरी कॉल से बचने की उम्मीद कर रहा था लेकिन मुझे लगता है कि आप सही हो सकते हैं। ऐसा लगता है कि जावा अभी तक पूरी तरह से छवि प्रसंस्करण नहीं मिला है! –
यह मेरा निष्कर्ष भी है! जावा छवि apis बस चूसना! मैं आलसीपन के आसपास काम कर सकता हूं, लेकिन खराब छवि गुणवत्ता सिर्फ स्वीकार्य नहीं है! मुझे उम्मीद है कि प्रासंगिक एपीआई को जावाएफएक्स 2.0 के साथ कुछ आवश्यक टीएलसी मिल जाएगा। – Kimble
आप स्पष्ट रूप से [जावा-छवि-स्केलिंग] (http://code.google.com/p/java-image-scaling/) में नहीं आए हैं। –