当前位置: 移动技术网 > IT编程>开发语言>Java > java实现图片压缩的思路与代码

java实现图片压缩的思路与代码

2019年07月22日  | 移动技术网IT编程  | 我要评论

本文实例为大家分享了java实现图片压缩的相关代码,供大家参考,具体内容如下

import java.awt.image;
import java.awt.image.bufferedimage;
import java.io.bytearrayoutputstream;
import java.io.ioexception;
import java.io.inputstream;
 
import javax.imageio.imageio;
 
public class imageprocess {
 /**
  * 图片
  */
 private image img; 
 /**
  * 宽度
  */
 private int width; 
 /**
  * 高度
  */
 private int height; 
 /**
  * 文件格式
  */
 private string imageformat;
 /** 
  * 构造函数 
  * @throws exception 
  */ 
 public imageprocess(inputstream in,string filename) throws exception{ 
   //构造image对象 
   img = imageio.read(in); 
   //得到源图宽 
   width = img.getwidth(null);
   //得到源图长 
   height = img.getheight(null);
   //文件格式
   imageformat = filename.substring(filename.lastindexof(".")+1);
 } 
 /** 
  * 按照宽度还是高度进行压缩 
  * @param w int 最大宽度 
  * @param h int 最大高度 
  */ 
 public byte[] resizefix(int w, int h) throws ioexception { 
   if (width / height > w / h) { 
     return resizebywidth(w); 
   } else { 
     return resizebyheight(h); 
   } 
 } 
 /** 
  * 以宽度为基准,等比例放缩图片 
  * @param w int 新宽度 
  */ 
 public byte[] resizebywidth(int w) throws ioexception { 
   int h = (int) (height * w / width); 
   return resize(w, h); 
 } 
 /** 
  * 以高度为基准,等比例缩放图片 
  * @param h int 新高度 
  */ 
 public byte[] resizebyheight(int h) throws ioexception { 
   int w = (int) (width * h / height); 
   return resize(w, h); 
 } 
 /** 
  * 强制压缩/放大图片到固定的大小 
  * @param w int 新宽度 
  * @param h int 新高度 
  */ 
 public byte[] resize(int w, int h) throws ioexception { 
   // scale_smooth 的缩略算法 生成缩略图片的平滑度的 优先级比速度高 生成的图片质量比较好 但速度慢 
   bufferedimage image = new bufferedimage(w, h,bufferedimage.type_int_rgb );  
   image.getgraphics().drawimage(img, 0, 0, w, h, null); // 绘制缩小后的图 
   bytearrayoutputstream baos = new bytearrayoutputstream();
   imageio.write(image, imageformat, baos);
   return baos.tobytearray();
 } 
}

以上就是本文的全部内容,希望对大家的学习有所帮助,轻松实现图片压缩操作。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网