import java.io.*;
import java.awt.*;
import java.awt.image.*;
import com.sun.image.codec.jpeg.*;
public class ImageUtil {
private String srcFile;
private String destFile;
private int width;
private int height;
private Image img;
public ImageUtil(String srcFile) throws IOException {
File _file = new File(srcFile);
this.srcFile = srcFile;
this.destFile = srcFile;
img = javax.imageio.ImageIO.read(_file);
width = img.getWidth(null);
height = img.getHeight(null);
}
public void resize(int w, int h) throws IOException {
BufferedImage _image = new BufferedImage(w, h,BufferedImage.TYPE_INT_RGB);
_image.getGraphics().drawImage(img, 0, 0, w, h, null);
FileOutputStream out = new FileOutputStream(destFile);
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
encoder.encode(_image);
out.close();
}
public void resize(double t) throws IOException {
int w = (int) (width * t);
int h = (int) (height * t);
resize(w, h);
}
public void resizeByWidth(int w) throws IOException {
int h = (int) (height * w / width);
resize(w, h);
}
public void resizeByHeight(int h) throws IOException {
int w = (int) (width * h / height);
resize(w, h);
}
public void resizeFix(int w, int h) throws IOException {
if (width / height > w / h) {
resizeByWidth(w);
} else {
resizeByHeight(h);
}
}
public int getSrcWidth() {
return width;
}
public int getSrcHeight() {
return height;
}
}
创建图片缩略图
最新推荐文章于 2025-04-25 11:38:28 发布
本文介绍了一个使用 Java 编写的图片处理工具类,该工具能够读取图片文件,并提供多种图片缩放方法,如按比例缩放、按宽度或高度缩放等。此工具利用了 Java 的 AWT 和 ImageIO 库来实现图片操作。
577

被折叠的 条评论
为什么被折叠?



