sunfruit[请访问http://www.fruitres.cn]

--我相信JAVA能走得更远 QQ:316228067

[原创]通过JAVA改变图片的像素Alpha值实现图片透明

    --sunfruit

    设置图片的每个象素Alpha,使得图片透明,核心代码如下

    private void setAlpha(ByteArrayOutputStream os) {
    /**
     * 增加测试项
     * 读取图片,绘制成半透明
     */
    try {

      ImageIcon imageIcon = new ImageIcon(os.toByteArray());
      BufferedImage bufferedImage = new BufferedImage(imageIcon.getIconWidth(),imageIcon.getIconHeight()
          , BufferedImage.TYPE_4BYTE_ABGR);
      Graphics2D g2D = (Graphics2D) bufferedImage.getGraphics();
      g2D.drawImage(imageIcon.getImage(), 0, 0,
                           imageIcon.getImageObserver());
      //循环每一个像素点,改变像素点的Alpha值
      int alpha = 100;
      for (int j1 = bufferedImage.getMinY(); j1 < bufferedImage.getHeight(); j1++) {
        for (int j2 = bufferedImage.getMinX(); j2 < bufferedImage.getWidth(); j2++) {
          int rgb = bufferedImage.getRGB(j2, j1);
          rgb = ( (alpha + 1) << 24) | (rgb & 0x00ffffff);
          bufferedImage.setRGB(j2, j1, rgb);
        }
      }
      g2D.drawImage(bufferedImage, 0, 0, imageIcon.getImageObserver());
     
      //生成图片为PNG

      ImageIO.write(bufferedImage, "png",  new File(图片路径));
    }
    catch (Exception e) {
      e.printStackTrace();
    }

  }

posted on 2007-05-20 00:20 sunfruit 阅读(12085) 评论(0)  编辑  收藏 所属分类: JAVA SE & EE


只有注册用户登录后才能发表评论。


网站导航: