解決java壓縮圖片透明背景變黑色的問題
阿新 • • 發佈:2019-01-30
public static BufferedImage resize(int faceWidth,BufferedImage srcImg,HttpServletRequest request) throws IOException{
int imgWidth = 0;
if(faceWidth>70 && faceWidth<120){
imgWidth = faceWidth*7/8;
}else if(faceWidth>60 && faceWidth<70){
imgWidth = faceWidth*11/10;
}else if(faceWidth < 60){
imgWidth = faceWidth*6/5;
}else{
imgWidth = faceWidth*4/5;
}
int imgHeight = imgWidth*srcImg.getHeight()/srcImg.getWidth();
//構建新的圖片
BufferedImage resizedImg = new BufferedImage(imgWidth,imgHeight,BufferedImage.TYPE_INT_RGB);
//將原圖放大或縮小後畫下來:並且保持png圖片放大或縮小後背景色是透明的而不是黑色
Graphics2D resizedG = resizedImg.createGraphics();
resizedImg = resizedG.getDeviceConfiguration().createCompatibleImage(imgWidth,imgHeight,Transparency.TRANSLUCENT);
resizedG.dispose();
resizedG = resizedImg.createGraphics();
Image from = srcImg.getScaledInstance(imgWidth, imgHeight, srcImg.SCALE_AREA_AVERAGING);
resizedG.drawImage(from, 0, 0, null);
resizedG.dispose();
return resizedImg;
}
int imgWidth = 0;
if(faceWidth>70 && faceWidth<120){
imgWidth = faceWidth*7/8;
}else if(faceWidth>60 && faceWidth<70){
imgWidth = faceWidth*11/10;
}else if(faceWidth < 60){
imgWidth = faceWidth*6/5;
}else{
imgWidth = faceWidth*4/5;
}
int imgHeight = imgWidth*srcImg.getHeight()/srcImg.getWidth();
//構建新的圖片
BufferedImage resizedImg = new BufferedImage(imgWidth,imgHeight,BufferedImage.TYPE_INT_RGB);
//將原圖放大或縮小後畫下來:並且保持png圖片放大或縮小後背景色是透明的而不是黑色
Graphics2D resizedG = resizedImg.createGraphics();
resizedImg = resizedG.getDeviceConfiguration().createCompatibleImage(imgWidth,imgHeight,Transparency.TRANSLUCENT);
resizedG.dispose();
resizedG = resizedImg.createGraphics();
Image from = srcImg.getScaledInstance(imgWidth, imgHeight, srcImg.SCALE_AREA_AVERAGING);
resizedG.drawImage(from, 0, 0, null);
resizedG.dispose();
return resizedImg;
}