public byte[] compressPic(byte[] data) {
if(data.length == 0){
return new byte[0];
}
Image img = null;
try {
img = ImageIO.read(new ByteArrayInputStream(data));
//将图片流转成图片,以便获取宽和高
BufferedImage imgs = toBufferedImage(img);
int w = imgs.getWidth();
int h = imgs.getHeight();
if(w > 480 && h<=800){
BufferedImage tag = new BufferedImage((int) 480, (int) h, BufferedImage.TYPE_INT_RGB);
tag.getGraphics().drawImage(img.getScaledInstance(480, h, Image.SCALE_SMOOTH), 0, 0, null);
ByteArrayOutputStream out = new ByteArrayOutputStream();
ImageIO.write( tag,"jpg",out);
out.close();
return out.toByteArray();
}else if(w > 480 && h>800){
BufferedImage tag = new BufferedImage((int) 480, (int) 800, BufferedImage.TYPE_INT_RGB);
tag.getGraphics().drawImage(img.getScaledInstance(480, 800, Image.SCALE_SMOOTH), 0, 0, null);
ByteArrayOutputStream out = new ByteArrayOutputStream();
ImageIO.write( tag,"jpg",out);
out.close();
return out.toByteArray();
}else if(w <= 480 && h>800){
BufferedImage tag = new BufferedImage((int) w, (int) 800, BufferedImage.TYPE_INT_RGB);
tag.getGraphics().drawImage(img.getScaledInstance(w, 800, Image.SCALE_SMOOTH), 0, 0, null);
ByteArrayOutputStream out = new ByteArrayOutputStream();
ImageIO.write( tag,"jpg",out);
out.close();
return out.toByteArray();
}else{
return data;
}
} catch (IOException e) {
e.printStackTrace();
}
return data;
}
public BufferedImage toBufferedImage(Image image) {
if (image instanceof BufferedImage) {
return (BufferedImage)image;
}
image = new ImageIcon(image).getImage();
BufferedImage bimage = null;
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
try {
int transparency = Transparency.OPAQUE;
GraphicsDevice gs = ge.getDefaultScreenDevice();
GraphicsConfiguration gc = gs.getDefaultConfiguration();
bimage = gc.createCompatibleImage(
image.getWidth(null), image.getHeight(null), transparency);
} catch (HeadlessException e) {
}
if (bimage == null) {
int type = BufferedImage.TYPE_INT_RGB;
bimage = new BufferedImage(image.getWidth(null), image.getHeight(null), type);
}
Graphics g = bimage.createGraphics();
g.drawImage(image, 0, 0, null);
g.dispose();
return bimage;
}