使用 Image.SCALE_SMOOTH算法进行图片压缩

本文介绍了一个Java类,用于实现图片的等比或非等比压缩,支持多种格式如jpg、bmp、png和gif等,提供了详细的使用方法和示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package test.gzt;


import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;


import javax.imageio.ImageIO;


import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;


public class CompressPic {


/*******************************************************************************
* 缩略图类(通用) 本java类能将jpg、bmp、png、gif图片文件,进行等比或非等比的大小转换。 具体使用方法
* compressPic(大图片路径,生成小图片路径,大图片文件名,生成小图片文名,生成小图片宽度,生成小图片高度,是否等比缩放(默认为true))
*/
private File file = null; // 文件对象
private String inputDir; // 输入图路径
private String outputDir; // 输出图路径
private String inputFileName; // 输入图文件名
private String outputFileName; // 输出图文件名
private int outputWidth = 100; // 默认输出图片宽
private int outputHeight = 100; // 默认输出图片高
private boolean proportion = true; // 是否等比缩放标记(默认为等比缩放)


public CompressPic() { // 初始化变量
inputDir = "";
outputDir = "";
inputFileName = "";
outputFileName = "";
outputWidth = 100;
outputHeight = 100;
}


public void setInputDir(String inputDir) {
this.inputDir = inputDir;
}


public void setOutputDir(String outputDir) {
this.outputDir = outputDir;
}


public void setInputFileName(String inputFileName) {
this.inputFileName = inputFileName;
}


public void setOutputFileName(String outputFileName) {
this.outputFileName = outputFileName;
}


public void setOutputWidth(int outputWidth) {
this.outputWidth = outputWidth;
}


public void setOutputHeight(int outputHeight) {
this.outputHeight = outputHeight;
}


public void setWidthAndHeight(int width, int height) {
this.outputWidth = width;
this.outputHeight = height;
}


/*
* 获得图片大小 传入参数 String path :图片路径
*/
public long getPicSize(String path) {
file = new File(path);
return file.length();
}
    public static void byte2File(byte[] buf, String filePath, String fileName){  
        BufferedOutputStream bos = null;  
        FileOutputStream fos = null;  
        File file = null;  
        try  
        {  
            File dir = new File(filePath);  
            if (!dir.exists() && dir.isDirectory())  
            {  
                dir.mkdirs();  
            }  
            file = new File(filePath + File.separator + fileName);  
            fos = new FileOutputStream(file);  
            bos = new BufferedOutputStream(fos);  
            bos.write(buf);  
        }  
        catch (Exception e)  
        {  
            e.printStackTrace();  
        }  
        finally  
        {  
            if (bos != null)  
            {  
                try  
                {  
                    bos.close();  
                }  
                catch (IOException e)  
                {  
                    e.printStackTrace();  
                }  
            }  
            if (fos != null)  
            {  
                try  
                {  
                    fos.close();  
                }  
                catch (IOException e)  
                {  
                    e.printStackTrace();  
                }  
            }  
        }
    }
        
public static byte[] File2byte(String filePath){  
        byte[] buffer = null;  
        try  
        {  
            File file = new File(filePath);  
            FileInputStream fis = new FileInputStream(file);  
            ByteArrayOutputStream bos = new ByteArrayOutputStream();  
            byte[] b = new byte[1024];  
            int n;  
            while ((n = fis.read(b)) != -1)  
            {  
                bos.write(b, 0, n);  
            }  
            fis.close();  
            bos.close();  
            buffer = bos.toByteArray();  
        }  
        catch (FileNotFoundException e)  
        {  
            e.printStackTrace();  
        }  
        catch (IOException e)  
        {  
            e.printStackTrace();  
        }  
        return buffer;  
    }


// 图片处理
@SuppressWarnings("restriction")
public String compressPic() {
try {
// 获得源文件
file = new File(inputDir);
//System.out.println(inputDir + inputFileName);
if (!file.exists()) {
System.out.println("文件不存在");
return "no";
//throw new Exception("文件不存在");
}
Image img = ImageIO.read(file);
// 判断图片格式是否正确
if (img.getWidth(null) == -1) {
System.out.println(" can't read,retry!" + "<BR>");
return "no";
} else {
int newWidth;
int newHeight;
// 判断是否是等比缩放
if (this.proportion == true) {
// 为等比缩放计算输出的图片宽度及高度
double rate1 = ((double) img.getWidth(null))
/ (double) outputWidth + 0.1;
double rate2 = ((double) img.getHeight(null))
/ (double) outputHeight + 0.1;
// 根据缩放比率大的进行缩放控制
double rate = rate1 > rate2 ? rate1 : rate2;
newWidth = (int) (((double) img.getWidth(null)) / rate);
newHeight = (int) (((double) img.getHeight(null)) / rate);
} else {
newWidth = outputWidth; // 输出的图片宽度
newHeight = outputHeight; // 输出的图片高度
}
BufferedImage tag = new BufferedImage((int) newWidth,
(int) newHeight, BufferedImage.TYPE_INT_RGB);


/*
* Image.SCALE_SMOOTH 的缩略算法 生成缩略图片的平滑度的 优先级比速度高 生成的图片质量比较好 但速度慢
*/
tag.getGraphics().drawImage(
img.getScaledInstance(newWidth, newHeight,
Image.SCALE_SMOOTH), 0, 0, null);
File f=new File(outputDir);
if (!f.exists()){
f.mkdirs(); 
}
FileOutputStream out = new FileOutputStream(outputDir
+ outputFileName);
// JPEGImageEncoder可适用于其他图片类型的转换
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
encoder.encode(tag);
out.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
return "ok";
}


// 图片处理
@SuppressWarnings("restriction")
public String compressPicByByte(byte[] picByte) {
try {
ByteArrayInputStream byteInput = new ByteArrayInputStream(picByte);
Image img = ImageIO.read(byteInput); 
// 判断图片格式是否正确
if (img.getWidth(null) == -1) {
System.out.println(" can't read,retry!" + "<BR>");
return "no";
} else {
int newWidth;
int newHeight;
// 判断是否是等比缩放
if (this.proportion == true) {
// 为等比缩放计算输出的图片宽度及高度
double rate1 = ((double) img.getWidth(null))
/ (double) outputWidth + 0.1;
double rate2 = ((double) img.getHeight(null))
/ (double) outputHeight + 0.1;
// 根据缩放比率大的进行缩放控制
double rate = rate1 > rate2 ? rate1 : rate2;
newWidth = (int) (((double) img.getWidth(null)) / rate);
newHeight = (int) (((double) img.getHeight(null)) / rate);
} else {
newWidth = outputWidth; // 输出的图片宽度
newHeight = outputHeight; // 输出的图片高度
}
BufferedImage tag = new BufferedImage((int) newWidth,
(int) newHeight, BufferedImage.TYPE_INT_RGB);


/*
* Image.SCALE_SMOOTH 的缩略算法 生成缩略图片的平滑度的 优先级比速度高 生成的图片质量比较好 但速度慢
*/
tag.getGraphics().drawImage(
img.getScaledInstance(newWidth, newHeight,
Image.SCALE_SMOOTH), 0, 0, null);
File f=new File(outputDir);
if (!f.exists()){
f.mkdirs(); 
}
FileOutputStream out = new FileOutputStream(outputDir
+ outputFileName);
// JPEGImageEncoder可适用于其他图片类型的转换
// JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
// encoder.encode(tag);
out.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
return "ok";
}


// 图片处理
@SuppressWarnings("restriction")
public byte[] compressPicToByteByByte(byte[] picByte) {
byte[] result = null;
try {
ByteArrayInputStream byteInput = new ByteArrayInputStream(picByte);
Image img = ImageIO.read(byteInput); 
// 判断图片格式是否正确
if (img.getWidth(null) == -1) {
System.out.println(" can't read,retry!" + "<BR>");
return result;
} else {
int newWidth;
int newHeight;
// 判断是否是等比缩放
if (this.proportion == true) {
// 为等比缩放计算输出的图片宽度及高度
double rate1 = ((double) img.getWidth(null))
/ (double) outputWidth + 0.1;
double rate2 = ((double) img.getHeight(null))
/ (double) outputHeight + 0.1;
// 根据缩放比率大的进行缩放控制
double rate = rate1 > rate2 ? rate1 : rate2;
newWidth = (int) (((double) img.getWidth(null)) / rate);
newHeight = (int) (((double) img.getHeight(null)) / rate);
} else {
newWidth = outputWidth; // 输出的图片宽度
newHeight = outputHeight; // 输出的图片高度
}
BufferedImage tag = new BufferedImage((int) newWidth,
(int) newHeight, BufferedImage.TYPE_INT_RGB);


/*
* Image.SCALE_SMOOTH 的缩略算法 生成缩略图片的平滑度的 优先级比速度高 生成的图片质量比较好 但速度慢
*/
tag.getGraphics().drawImage(
img.getScaledInstance(newWidth, newHeight,
Image.SCALE_SMOOTH), 0, 0, null);
ByteArrayOutputStream out = new ByteArrayOutputStream();
boolean flag = ImageIO.write(tag, "JPG", out);
result = out.toByteArray();
out.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
return result;
}


public String compressPic(String outputDir, String inputFileName,
String outputFileName) {
// 输出图路径
this.outputDir = outputDir;
// 输入图文件名
this.inputFileName = inputFileName;
// 输出图文件名
this.outputFileName = outputFileName;
return compressPic();
}


public String compressPic(String inputDir, String outputDir,
String inputFileName, String outputFileName, int width, int height,
boolean gp) {
// 输入图路径
this.inputDir = inputDir;
// 输出图路径
this.outputDir = outputDir;
// 输入图文件名
this.inputFileName = inputFileName;
// 输出图文件名
this.outputFileName = outputFileName;
// 设置图片长宽
setWidthAndHeight(width, height);
// 是否是等比缩放 标记
this.proportion = gp;
return compressPic();
}


/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
CompressPic compressPic = new CompressPic();
compressPic.setInputDir("D:" + File.separator + "aaron" + File.separator + "pic" + File.separator + "IMG_0001.JPG");
compressPic.setOutputDir("D:" + File.separator + "aaron" + File.separator + "pic" + File.separator);
compressPic.setOutputFileName("test3.JPG");
// System.out.println(compressPic.compressPic());
// byte[] picByte = compressPic.File2byte("D:" + File.separator + "aaron" + File.separator + "pic" + File.separator + "IMG_0001.JPG");
// if (picByte.length != 0) {
// System.out.println(compressPic.compressPicByByte(picByte));
// }else{
// System.out.println("error");
// }

byte[] picByte = compressPic.File2byte("D:" + File.separator + "aaron" + File.separator + "pic" + File.separator + "IMG_0001.JPG");
if (picByte.length != 0) {
byte[] result = compressPic.compressPicToByteByByte(picByte);
compressPic.byte2File(result, "D:" + File.separator + "aaron" + File.separator + "pic" + File.separator, "test_a.JPG");
System.out.println("ok");
} else {
System.out.println("error");
}
}


}



参考网址:

http://blog.youkuaiyun.com/p793049488/article/details/42295237

http://www.iteye.com/topic/266585

package com; import java.awt.image.BufferedImage; import com.sun.image.codec.jpeg.JPEGCodec; import com.sun.image.codec.jpeg.JPEGImageEncoder; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import javax.imageio.ImageIO; /** * 图片压缩 * @author 86183 */ @SuppressWarnings("restriction") public class yasuo { static BufferedImage img = null; public yasuo(String fileName) throws IOException { try { File imageFile = new File(fileName); if (!imageFile.exists()) { System.err.println("文件不存在: " + imageFile.getAbsolutePath()); return; } BufferedImage img = ImageIO.read(imageFile); if (img == null) { System.out.println("不支持的图片格式或文件已损坏"); } } catch (IOException e) { System.err.println("读取文件错误: " + e.getMessage()); } // File file = new File(fileName);// 读入文件 // img = ImageIO.read(file); // 构造Image对象 } /** * 强制压缩/放大图片到固定的大小 * @param w int 新宽度 * @param h int 新高度 */ public void resize(int w, int h, String toPic) throws IOException { // SCALE_SMOOTH 的缩略算法 生成缩略图片的平滑度的 优先级比速度高 生成的图片质量比较好 但速度慢 BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB); image.getGraphics().drawImage(img, 0, 0, w, h, null); // 绘制缩小后的图 File destFile = new File(toPic); FileOutputStream out = new FileOutputStream(destFile); // 输出到文件流 // 可以正常实现bmp、png、gif转jpg JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); encoder.encode(image); // JPEG编码 out.close(); } }请将这个代码中的resize方法中的实现换成调用哈夫曼树的算法进行压缩
最新发布
07-09
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值