Java图片处理工具类
发布时间:2020-05-24 15:55:04 所属栏目:Java 来源:互联网
导读:Java图片处理工具类
|
下面是脚本之家 jb51.cc 通过网络收集整理的代码片段。 脚本之家小编现在分享给大家,也给大家做个参考。 import java.io.*;
import java.util.Date;
import java.awt.*;
import java.awt.image.*;
import javax.imageio.ImageIO;
import com.sun.image.codec.jpeg.*;
/**
* 图片压缩处理
*
* @author kuang hj
*/
public class ImgCompressUtils
{
// 图片对象
private Image img;
// 原图的宽度
private int width;
// 原图的高度
private int height;
private static BufferedImage image;
@SuppressWarnings("deprecation")
public static void main(String[] args)
throws Exception
{
System.out.println("开始:" + new Date().toLocaleString());
ImgCompressUtils imgCom = new ImgCompressUtils("D:jjj.jpg");
// 处理图片得到 image
imgCom.resizeFix(80,80);
// 输出结果文件
outputNewFile("D:result.jpg",image);
System.out.println("结束:" + new Date().toLocaleString());
}
/**
* 构造函数 取到需要处理的图片,得到宽 和 高
*/
public ImgCompressUtils(String fileName)
throws IOException
{
File file = new File(fileName);// 读入文件
img = ImageIO.read(file); // 构造Image对象
width = img.getWidth(null); // 得到源图宽
height = img.getHeight(null); // 得到源图长
}
/**
* 按照宽度还是高度进行压缩
*
* @param destwidth int 最大宽度
* @param destheight int 最大高度
*/
public void resizeFix(int destwidth,int destheight)
throws IOException
{
if (width / height > destwidth / destheight)
{
resizeByWidth(destwidth);
}
else
{
resizeByHeight(destheight);
}
}
/**
* 以宽度为基准,等比例放缩图片
*
* @param destwidth int 新宽度
*/
public void resizeByWidth(int destwidth)
throws IOException
{
int tmph = (int)(height * destwidth / width);
resize(destwidth,tmph);
}
/**
* 以高度为基准,等比例缩放图片
*
* @param destheight int 新高度
*/
public void resizeByHeight(int destheight)
throws IOException
{
int tmpw = (int)(width * destheight / height);
resize(tmpw,destheight);
}
/**
* 强制压缩/放大图片到固定的大小
*
* @param w int 新宽度
* @param h int 新高度
*/
public BufferedImage resize(int destwidth,int destheight)
{
// SCALE_SMOOTH 的缩略算法 生成缩略图片的平滑度的 优先级比速度高 生成的图片质量比较好 但速度慢
image = new BufferedImage(destwidth,destheight,BufferedImage.TYPE_INT_RGB);
// 绘制缩小后的图
image.getGraphics().drawImage(img,destwidth,null);
return image;
}
/**
* 新生成的压缩文件 <一句话功能简述> <功能详细描述>
*
* @param path
* @param image
* @see [类、类#方法、类#成员]
*/
public static void outputNewFile(String path,BufferedImage image)
{
try
{
File destFile = new File(path);
FileOutputStream out = new FileOutputStream(destFile); // 输出到文件流
// 可以正常实现bmp、png、gif转jpg
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
encoder.encode(image); // JPEG编码
out.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
以上是脚本之家(jb51.cc)为你收集整理的全部代码内容,希望文章能够帮你解决所遇到的程序开发问题。 如果觉得脚本之家网站内容还不错,欢迎将脚本之家网站推荐给程序员好友。 (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
