不确定我做错了什么,但保存的图像与原来的~500px高相同。我试图将图像设置为100px高并保持aspectratio相同。然后保存较小的版本。
BufferedImage original = ImageIO.read(inputStream);
Integer width = original.getWidth();
float aspectratio = (float)original.getWidth()/(float)original.getHeight();
Integer newwidth= Math.round(100*aspectratio);
BufferedImage scaledImage = new BufferedImage(newwidth,100,original.getType());
Graphics2D g = scaledImage.createGraphics();
g.drawImage(scaledImage,0,0,null);
g.dispose();
ImageIO.write(scaledImage, "PNG", result);
答案 0 :(得分:0)
问题是drawImage(Image, int, int, ImageObserver)
无法缩放图像。此外,您正在将图像绘制到自身。您需要使用缩放图像的drawImage
重载,如下所示:
// ...
Graphics2D g = scaledImage.createGraphics();
g.drawImage(original, 0, 0, scaledImage.getWidth(), scaledImage.getHeight(), 0, 0, original.getWidth(), original.getHeight(), null);
// ...
查看JavaDocs for Graphics
上的更多信息。
答案 1 :(得分:0)
小例子,取决于你的代码
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
public class ImageScaler {
public static void main(String[] args) {
try {
// Load the original image
BufferedImage image = ImageIO.read(new File(("PATH_TO_YOUR_ORIGINAL_IMAGE")));
float wh = (float)image.getWidth()/(float)image.getHeight();
int aspect = Math.round(100*wh);
// get a scaledInstance from the original image depending on your
// calculated aspectRation
Image scaledInstance = image.getScaledInstance(aspect, 100, Image.SCALE_SMOOTH);
// convert the Image to BufferedImage
BufferedImage bi = getScaledBufferedImage(scaledInstance);
// Write it out
File outputFile = new File("PATH_TO_SAVE_THE_SCALED_VERSION");
ImageIO.write(bi, "png", outputFile);
} catch (IOException ex) {
Logger.getLogger(ImageScaler.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* Converts a given Image instance to a BufferedImage
* @param image
* @return BufferedImage
*/
private static BufferedImage getScaledBufferedImage(final Image image) {
// check if image is instanceof BufferedImages
if(image instanceof BufferedImage) {
return (BufferedImage)image;
}
// create a new BufferedImage
BufferedImage bi = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_ARGB);
// get the Graphics Object from the BufferedImage
Graphics g = bi.getGraphics();
// draw the Image to the BufferedImage
g.drawImage(image, 0, 0, null);
// dispose the Graphics
g.dispose();
return bi;
}
}
帕特里克