主要使用到的是Java.awt.image.*包,继续RGBImageFilter类,对图片的像素进行alpha(透明度)进行修改,下面以applet为例: import java.applet.*; import java.awt.*; import java.awt.event.*; import java.awt.font.*; import java.awt.image.*;
public class applet6 extends Applet { MediaTracker mt; Image img=null; Image im=null; ImageFilter imgf=null; FilteredImageSource fis=null; public void init() { img=this.getImage(this.getCodeBase(),"d.jpg"); mt=new MediaTracker(this); mt.addImage(img,0); try { mt.waitForAll(0); } catch(Exception ex) {System.err.println(ex.toString());} im=this.createImage(100,100);//建立新的图片,用于输入文字,以便接下来进行透明处理 Graphics g2=im.getGraphics(); g2.setFont(new Font("宋体",Font.BOLD,15)); g2.drawString("半透明文字",10,50); imgf=new myImage(100,100,100);//调用自定义类进行对象构造 fis=new FilteredImageSource(im.getSource(),imgf);//对图象的源(图象生产者)进行过滤处理,构造出FilteredImageSource对象实例 im=this.createImage(fis);//通过FilteredImageSource实例生成Image }
public void paint(Graphics g) { g.drawImage(img,0,0,this);//画出图片 g.drawImage(im,100,100,this);//添加半透明文字 } }
class myImage extends RGBImageFilter {//抽象类RGBImageFilter是ImageFilter的子类,继续它实现图象ARGB的处理 int width=0; int height=0; int alpha=0; public myImage(int width,int height,int alpha) {//构造器,用来接收需要过滤图象的尺寸,以及透明度 this.canFilterIndexColorModel=true; //TransparentImageFilter类继续自RGBImageFilter,它的构造函数要求传入原始图象的宽度和高度。该类实现了filterRGB抽象函数,缺省的方式下,该函数将x,y所标识的象素的ARGB值传入,程序员按照一定的程序逻辑处理后返回该象素新的ARGB值 this.width=width; this.height=height; this.alpha=alpha; }
public int filterRGB(int x,int y,int rgb) { DirectColorModel dcm=(DirectColorModel)ColorModel.getRGBdefault(); //DirectColorModel类用来将ARGB值独立分解出来 int red=dcm.getRed(rgb); int green=dcm.getGreen(rgb); int blue=dcm.getBlue(rgb); if(red==255&&green==255&&blue==255)//假如像素为白色,则让它透明 alpha=0; return alpha<<24red<<16green<<8blue;//进行标准ARGB输出以实现图象过滤 } }
|