JAva圧縮ピクチャ、等比例圧縮ピクチャ
3640 ワード
JAvaは画像処理のサポートを提供し、使用が簡単で、機能も比較的強い(圧縮後の画像品質の設定をサポートするなど)、コードを直接見ればいい.
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* Created by halfsking on 2016/3/29.
*/
public class ImageCompressUtil {
// private static final ILog LOG = LogFactory.getLog(ImageCompressUtil.class);
public static byte[] compressImage(byte[] data)
{
return compressImage(data,600,400,0.85f);
}
public static byte[] compressImage(byte[] data,int width,int height)
{
return compressImage(data,width,height,0.85f);
}
public static byte[] compressImage(byte[] data,int width,int height,float quality)
{
width = width>600?600:width;// 600
height = height>400?400:height;// 400
quality = quality<0.8f?0.8f:quality;
int maxLength = 71*1024;//70K
if(data==null || data.lengthori_width || height>ori_height)
{
return data;
}
float ori_rate = (float)ori_width / (float)ori_height;
float rate = (float)width / (float)height;
if (ori_rate > rate) {
return compressByWidth(ori_width, ori_height, width, oriImg, quality);
} else {
return compressByHeight(ori_width, ori_height, height, oriImg, quality);
}
} catch (IOException e) {
LOG.error("ImageCompressUtil compressImage IOException failed,",e);
}
LOG.warn("ImageCompressUtil compressImage failed,now return the origin data.");
return data;
}
/**
* ,
* @param w int
*/
private static byte[] compressByWidth(int ori_width,int ori_height,int w,Image oriImg,float quality) throws IOException {
int h = (int) (ori_height * w / ori_width);
return compress(w, h, oriImg, quality);
}
/**
* ,
* @param h int
*/
private static byte[] compressByHeight(int ori_width,int ori_height,int h,Image oriImg,float quality) throws IOException {
int w = (int) (ori_width * h / ori_height);
return compress(w, h, oriImg, quality);
}
/**
* /
* @param w int
* @param h int
*/
private static byte[] compress(int w, int h,Image oriImg,float quality) throws IOException {
BufferedImage image = new BufferedImage(w, h,BufferedImage.TYPE_INT_RGB );
// SCALE_SMOOTH
//image.getGraphics().drawImage(img, 0, 0, w, h, null); //
image.getGraphics().drawImage(oriImg.getScaledInstance(w, h, Image.SCALE_SMOOTH), 0,0,null);
ByteArrayOutputStream out = new ByteArrayOutputStream();
// bmp、png、gif jpg
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
JPEGEncodeParam jep = JPEGCodec.getDefaultJPEGEncodeParam(image);
/* */
jep.setQuality(quality, true);
encoder.encode(image, jep);// JPEG
return out.toByteArray();
}
}