如題,以下為通過java實現的針對圖片的背景透明及透明度處理,供大家需要時參考:
/** * 設置源圖片為背景透明,並設置透明度 * @param srcFile 源圖片 * @param desFile 目標文件 * @param alpha 透明度 * @param formatName 文件格式 * @throws IOException */ public static void transparentImage(String srcFile,String desFile,int alpha,String formatName) throws IOException{ BufferedImage temp = ImageIO.read(new File(srcFile));//取得圖片 transparentImage(temp, desFile, alpha, formatName); } /** * 設置源圖片為背景透明,並設置透明度 * @param srcImage 源圖片 * @param desFile 目標文件 * @param alpha 透明度 * @param formatName 文件格式 * @throws IOException */ public static void transparentImage(BufferedImage srcImage, String desFile, int alpha, String formatName) throws IOException { int imgHeight = srcImage.getHeight();//取得圖片的長和寬 int imgWidth = srcImage.getWidth(); int c = srcImage.getRGB(3, 3); //防止越位 if (alpha < 0) { alpha = 0; } else if (alpha > 10) { alpha = 10; } BufferedImage bi = new BufferedImage(imgWidth, imgHeight, BufferedImage.TYPE_4BYTE_ABGR);//新建一個類型支持透明的BufferedImage for(int i = 0; i < imgWidth; ++i)//把原圖片的內容復制到新的圖片,同時把背景設為透明 { for(int j = 0; j < imgHeight; ++j) { //把背景設為透明 if(srcImage.getRGB(i, j) == c){ bi.setRGB(i, j, c & 0x00ffffff); } //設置透明度 else{ int rgb = bi.getRGB(i, j); rgb = ((alpha * 255 / 10) << 24) | (rgb & 0x00ffffff); bi.setRGB(i, j, rgb); } } } ImageIO.write(bi, StringUtils.isEmpty(formatName)?FORMAT_PNG:formatName, new File(desFile)); }