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; }
java 压缩图片背景变黑_解决java压缩图片透明背景变黑色的问题
最新推荐文章于 2023-10-31 11:00:26 发布
该代码段实现了一个根据面部宽度智能调整图片尺寸的函数。它使用不同的比例因子来确定新图像的宽度,然后计算相应的高度,保持原图像的宽高比。最后,使用Graphics2D和ScaledInstance方法创建并绘制缩放后的图像,确保背景透明。
摘要由CSDN通过智能技术生成