java壓縮圖片記憶體大小,但不改變解析度大小,第二種方式
阿新 • • 發佈:2019-02-10
/**
* @Title: compressPic
* @Description: 壓縮圖片,通過壓縮圖片質量,保持原圖大小
* @param quality:0-1
* @return byte[]
* @throws
*/
public static byte[] compressPic(byte[] imageByte,float quality) {
byte[] inByte = null;
try {
ByteArrayInputStream byteInput = new ByteArrayInputStream(imageByte);
Image img = ImageIO.read(byteInput);
float newWidth = img.getWidth(null);
float newHeight = img.getHeight(null);
Image image = img.getScaledInstance((int) newWidth,(int) newHeight, Image.SCALE_SMOOTH);
// 縮放影象
BufferedImage tag = new BufferedImage((int) newWidth,
(int) newHeight, BufferedImage.TYPE_INT_RGB);
Graphics2D g = tag.createGraphics();
g.drawImage(image, 0, 0, null); // 繪製縮小後的圖
g.dispose();
ByteArrayOutputStream out = new ByteArrayOutputStream(imageByte.length);
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
JPEGEncodeParam jep=JPEGCodec.getDefaultJPEGEncodeParam(tag);
/* 壓縮質量 */
jep.setQuality((float)0.6, true);
encoder.encode(tag, jep);
inByte = out.toByteArray();
out.close();
} catch (IOException ex) {
ex.printStackTrace();
}
return inByte;
}
* @Title: compressPic
* @Description: 壓縮圖片,通過壓縮圖片質量,保持原圖大小
* @param quality:0-1
* @return byte[]
* @throws
*/
public static byte[] compressPic(byte[] imageByte,float quality) {
byte[] inByte = null;
try {
ByteArrayInputStream byteInput = new ByteArrayInputStream(imageByte);
Image img = ImageIO.read(byteInput);
float newWidth = img.getWidth(null);
float newHeight = img.getHeight(null);
Image image = img.getScaledInstance((int) newWidth,(int) newHeight, Image.SCALE_SMOOTH);
// 縮放影象
BufferedImage tag = new BufferedImage((int) newWidth,
(int) newHeight, BufferedImage.TYPE_INT_RGB);
Graphics2D g = tag.createGraphics();
g.drawImage(image, 0, 0, null); // 繪製縮小後的圖
g.dispose();
ByteArrayOutputStream out = new ByteArrayOutputStream(imageByte.length);
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
JPEGEncodeParam jep=JPEGCodec.getDefaultJPEGEncodeParam(tag);
/* 壓縮質量 */
jep.setQuality((float)0.6, true);
encoder.encode(tag, jep);
inByte = out.toByteArray();
out.close();
} catch (IOException ex) {
ex.printStackTrace();
}
return inByte;
}