gpt4 book ai didi

java - JAVA 中 JPG 图像大小调整程序的 0 字节文件

转载 作者:行者123 更新时间:2023-12-02 06:37:30 25 4
gpt4 key购买 nike

我在使用以下代码调整图像(JPG 文件)大小时遇到​​问题:

import java.awt.AlphaComposite;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.logging.Logger;
import java.util.logging.Level;
import java.io.IOException;
import javax.imageio.ImageIO;

public class ResizeImage {


/**
*
* @param sourceImg
* The source of the image to resize.
* @param Width
* The maximum width you want the new image to be, use 0 for
* source width.
* @param Height
* The maximum height you want the new image to be, use 0 for
* source height.
* @return true if successful and false if unsuccessful.
*/

public static String resizeImage(String sourceImg, Integer Width,
Integer Height) {

BufferedImage origImage;
BufferedImage resizedImage = null;
// String tDir = System.getProperty("java.io.tmpdir");
String imagePath;

try {

File resizedFile = File.createTempFile("ResizedImmoIMG", ".jpg");
imagePath = resizedFile.getAbsolutePath();
origImage = ImageIO.read(new File(sourceImg));
int type = origImage.getType() == 0 ? BufferedImage.TYPE_INT_ARGB
: origImage.getType();

// *Special* if the width or height is 0 use image src dimensions
if (Width == 0) {
Width = origImage.getWidth();
}
if (Height == 0) {
Height = origImage.getHeight();
}

int fHeight = Height;
int fWidth = Width;

// Work out the resized width/height
if (origImage.getHeight() > Height || origImage.getWidth() > Width) {
fHeight = Height;
int wid = Width;
float sum = (float) origImage.getWidth()
/ (float) origImage.getHeight();
fWidth = Math.round(fHeight * sum);

if (fWidth > wid) {
// rezise again for the width this time
fHeight = Math.round(wid / sum);
fWidth = wid;
}
}

resizedImage = new BufferedImage(fWidth, fHeight, type);

Graphics2D g2d = resizedImage.createGraphics();
g2d.setComposite(AlphaComposite.Src);

g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2d.setRenderingHint(RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_QUALITY);
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);

g2d.drawImage(origImage, 0, 0, fWidth, fHeight, null);
g2d.dispose();

ImageIO.write(resizedImage, ".jpg", resizedFile);
System.out.println(imagePath);

} catch (IOException ex) {
Logger.getLogger(ResizeImage.class.getName()).log(Level.SEVERE,
null, ex);
return null;
}
return imagePath;
}

}

程序应该调整源图像的大小,并将其保存在系统临时目录中。但我得到的只是临时目录中的 0 字节 JPG 文件。我看不出我哪里做错了:(

有人可以给我一些建议或提示吗?

问候

THE-E

最佳答案

作为 ImageIO.write 方法的第二个参数,您必须传递图像格式而不是文件扩展名。尝试简单地使用“jpg”而不是“.jpg”。

Writing/Saving an Image

关于java - JAVA 中 JPG 图像大小调整程序的 0 字节文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19483695/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com