[英]Java - How to pad and resize image without cropping?
我需要從(2:3)到(3:4)的比例調整很多圖像的大小。
圖片目前為800像素x 1200像素。 我需要它們最終為600像素x 800像素,而無需裁剪。
我可以知道哪些庫可供我進行填充和調整大小而無需在Java中裁剪嗎?
從當前的Image(假設一個java.awt.Image
)中,您可以使用:
Image.getScaledInstance(w,h,h)
作為方法 Image.SCALE_SMOOTH
作為調整大小的算法 這些步驟:
width
和height
width
和height
以獲得縮放的圖像 static BufferedImage pad(BufferedImage image, double width, double height, Color pad) {
double ratioW = image.getWidth() / width;
double ratioH = image.getHeight() / height;
double newWidth = width, newHeight = height;
int fitW = 0, fitH = 0;
BufferedImage resultImage;
Image resize;
//padding width
if (ratioW < ratioH) {
newWidth = image.getWidth() / ratioH;
newHeight = image.getHeight() / ratioH;
fitW = (int) ((width - newWidth) / 2.0);
}//padding height
else if (ratioH < ratioW) {
newWidth = image.getWidth() / ratioW;
newHeight = image.getHeight() / ratioW;
fitH = (int) ((height - newHeight) / 2.0);
}
resize = image.getScaledInstance((int) newWidth, (int) newHeight, Image.SCALE_SMOOTH);
resultImage = new BufferedImage((int) width, (int) height, image.getType());
Graphics g = resultImage.getGraphics();
g.setColor(pad);
g.fillRect(0, 0, (int) width, (int) height);
g.drawImage(resize, fitW, fitH, null);
g.dispose();
return resultImage;
}
用作
BufferedImage image = ...;
BufferedImage result = pad(image, 600, 800, Color.white);
我認為ffmpeg可以幫助您處理圖像。 例如, 使用ffmpeg調整圖像大小
使用以下代碼成功做到了這一點:“ w”是您需要在每一側填充的數量。
BufferedImage newImage = new BufferedImage(image.getWidth()+2*w, image.getHeight(),
image.getType());
Graphics g = newImage.getGraphics();
g.setColor(Color.white);
g.fillRect(0,0,image.getWidth()+2*w,image.getHeight());
g.drawImage(image, w, 0, null);
g.dispose();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.