java改变png图片的透明度

来源:互联网 发布:淘宝积分是什么意思 编辑:程序博客网 时间:2024/04/27 13:27

java改变png图片的透明度

    博客分类: 
  • java
javapng 
Java代码  收藏代码
  1. package cn;  
  2.   
  3. import java.awt.Graphics2D;  
  4. import java.awt.image.BufferedImage;  
  5. import java.io.ByteArrayOutputStream;  
  6. import java.io.File;  
  7. import java.io.FileInputStream;  
  8.   
  9. import javax.imageio.ImageIO;  
  10. import javax.swing.ImageIcon;  
  11.   
  12. public class ChangeImageAlpha {  
  13.   
  14. /** 
  15. * 改变png图片的透明度 
  16. * @param srcImageFile 源图像地址 
  17. * @param descImageDir 输出图片的路径和名称 
  18. * @param alpha 输出图片的透明度1-10 
  19. */  
  20. private static void setAlpha(String srcImageFile, String descImageDir,int alpha) {  
  21.   
  22.     try {  
  23.     //读取图片  
  24.     FileInputStream stream = new FileInputStream(new File(srcImageFile));// 指定要读取的图片  
  25.   
  26.     // 定义一个字节数组输出流,用于转换数组  
  27.     ByteArrayOutputStream os = new ByteArrayOutputStream();  
  28.   
  29.     byte[] data =new byte[1024];// 定义一个1K大小的数组  
  30.     while (stream.read(data) != -1) {  
  31.     os.write(data);  
  32.     }  
  33.   
  34.         ImageIcon imageIcon = new ImageIcon(os.toByteArray());  
  35.         BufferedImage bufferedImage = new BufferedImage(imageIcon.getIconWidth(), imageIcon.getIconHeight(),  
  36.         BufferedImage.TYPE_4BYTE_ABGR);  
  37.         Graphics2D g2D = (Graphics2D) bufferedImage.getGraphics();  
  38.         g2D.drawImage(imageIcon.getImage(), 00, imageIcon.getImageObserver());  
  39.   
  40.         //判读透明度是否越界  
  41.         if (alpha < 0) {  
  42.         alpha = 0;  
  43.         } else if (alpha > 10) {  
  44.         alpha = 10;  
  45.         }  
  46.   
  47.         // 循环每一个像素点,改变像素点的Alpha值  
  48.         for (int j1 = bufferedImage.getMinY(); j1 < bufferedImage.getHeight(); j1++) {  
  49.         for (int j2 = bufferedImage.getMinX(); j2 < bufferedImage.getWidth(); j2++) {  
  50.         int rgb = bufferedImage.getRGB(j2, j1);  
  51.         rgb = ((alpha * 255 / 10) << 24) | (rgb & 0x00ffffff);  
  52.         bufferedImage.setRGB(j2, j1, rgb);  
  53.         }  
  54.         }  
  55.         g2D.drawImage(bufferedImage, 00, imageIcon.getImageObserver());  
  56.   
  57.         // 生成图片为PNG  
  58.   
  59.         ImageIO.write(bufferedImage, "png"new File(descImageDir));  
  60.   
  61.     } catch (Exception e) {  
  62.     e.printStackTrace();  
  63.     }  
  64.   
  65. }  
  66.   
  67. public static void main(String[] args) {  
  68. setAlpha("F:/gfsciy20110326fscjy1999ppp.png","F:/gfsciy20110326fscjy1999ppp-4.png"4);  
  69.   
  70. }  
  71.   
  72.   
0 0