[英]Generating square thumbnails in Java by cutting (without destroying aspect ratio)?
我正在尋找一種在Java中創建正方形縮略圖(250px×250px)而又不破壞寬高比的方法,這意味着如果圖像是矩形,且一側長於另一側,則應將不適合的部分剪掉廣場。 目前,我正在這樣做:
public static void createThumbnail(File file, String extension)
throws IOException {
BufferedImage img = new BufferedImage(
250, 250, BufferedImage.TYPE_INT_RGB);
img.createGraphics().drawImage(
ImageIO.read(file).getScaledInstance(
250, 250, Image.SCALE_SMOOTH), 0, 0, null);
ImageIO.write(img, extension, new File(
"./public/images/thumbs/" + file.getName()));
}
但是,它並不是切割圖像的一部分,而是將其壓縮到適合250×250正方形的范圍。
您正在使用getScaledInstance()
,它將僅放大或縮小圖像以使其符合您提供的大小。
看看getSubimage()
。 您最可能希望首先獲得具有與目標大小相同的長寬比(正方形)的子圖像,然后在其上應用getScaledInstance()
。 這樣,您只是以相同的寬高比進行縮小,而不會得到任何擠壓效果。
所以這樣的事情應該起作用。 假設要在裁剪時保留中間部分。
Image getThumbnail(File file) {
BufferedImage original = ImageIO.read(file);
//assuming we want a square thumbnail here
int side = Math.min(original.getWidth(), original.getHeight());
int x = (original.getWidth() - side) / 2;
int y = (original.getHeight() - side) / 2;
BufferedImage cropped = original.getSubimage(x, y, side, side);
return cropped.getScaledInstance(250, 250, Image.SCALE_SMOOTH);
}
(我自己沒有嘗試過,如果有任何問題,請告訴我。)
然后,您可以將其傳遞到drawImage()
創建新的呈現的BufferedImage
,並將其保存到文件中。
BufferedImage img = new BufferedImage(250, 250, BufferedImage.TYPE_INT_RGB);
img.createGraphics().drawImage(getThumbnail(file), 0, 0, null);
ImageIO.write(img, extension, new File("./public/images/thumbs/" + file.getName()));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.