62,622
社区成员
发帖
与我相关
我的任务
分享
File _file = new File("d:\\1.jpg"); //读入文件
Image src = javax.imageio.ImageIO.read(_file); //构造Image对象
int wideth=src.getWidth(null); //得到源图宽
int height=src.getHeight(null); //得到源图长
BufferedImage tag = new BufferedImage(wideth/2,height/2,BufferedImage.TYPE_INT_RGB);
tag.getGraphics().drawImage(src,0,0,wideth/2,height/2,null); //绘制缩小后的图
FileOutputStream out=new FileOutputStream("D:\\newfile.jpg"); //输出到文件流
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
encoder.encode(tag); //近JPEG编码
out.close();
private void compressImageFile() {
JFileChooser fileChooser = new JFileChooser("d://");
fileChooser.showOpenDialog(this);
File file = fileChooser.getSelectedFile();
if (null != file && file.exists()) {
Toolkit toolkit = Toolkit.getDefaultToolkit();
Image srcImage = toolkit.getImage(file.getAbsolutePath()); // 构造Image对象
int wideth = -1;
int height = -1;
boolean flag = true;
while (flag) {
wideth = srcImage.getWidth(null); // 得到源图宽
height = srcImage.getHeight(null); // 得到源图长
System.out.println("wideth:" + wideth + " height:" + height);
if (wideth > 0 && height > 0) { // 因为 Toolkit.getImage 是异步读取,如果
// wideth 和 height
// 都大于0,表明图片已经加载完毕
// imageCanvas.setImage(srcImage);
flag = false;
} else {
try {
Thread.sleep(10);
} catch (Exception e) {
e.printStackTrace();
}
}
}
// 加载完毕,输出
int w = 1024;
float s = (float) wideth / 1024.0f;
int h = (int) ((float) height / s);
BufferedImage bufferedImage = new BufferedImage(w, h,
BufferedImage.TYPE_INT_RGB);
// bufferedImage.getGraphics().drawImage(srcImage, 0, 0, 1024,
// 768, null); // 绘制缩小后的图
boolean flag2 = false;
while (!(flag2 = bufferedImage.getGraphics().drawImage(srcImage, 0,
0, w, h, this))) {
try {
Thread.sleep(10);
} catch (Exception e) {
e.printStackTrace();
}
}
try {
File outputFile = new File("d://hhh.jpg");
if (!outputFile.exists()) {
outputFile.createNewFile();
}
FileOutputStream out = new FileOutputStream(outputFile); // 输出到文件流
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
encoder.encode(bufferedImage); // 近JPEG编码
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}