67,513
社区成员
发帖
与我相关
我的任务
分享
@SuppressWarnings("finally")
public static byte[] scale(byte[] bytes , double width, double height) {
BufferedImage bufferedImage = null;
BufferedImage bufTarget = null;
try {
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
bufferedImage = ImageIO.read(bais);
double sx = width / bufferedImage.getWidth();
double sy = height / bufferedImage.getHeight();
int type = bufferedImage.getType();
if (type == BufferedImage.TYPE_CUSTOM) {
ColorModel cm = bufferedImage.getColorModel();
WritableRaster raster = cm.createCompatibleWritableRaster((int)width, (int)height);
boolean alphaPremultiplied = cm.isAlphaPremultiplied();
bufTarget = new BufferedImage(cm, raster, alphaPremultiplied, null);
} else {
bufTarget = new BufferedImage((int)width, (int)height, type);
}
Graphics2D g = bufTarget.createGraphics();
g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g.drawRenderedImage(bufferedImage, AffineTransform.getScaleInstance(sx, sy));
g.dispose();
if(bufTarget != null){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(bufTarget, "jpeg", baos);
byte[] result = baos.toByteArray();
return result;
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
图片压缩,把图片的byte字节和需要重新生成的大小传递进来即可.