在java的GUI上放置图片,并在图片上输出半透明文字

王朝java/jsp·作者佚名  2006-01-08
窄屏简体版  字體: |||超大  

问此问题的人也不少,把以前做的代码拿出来整理为文档,希望对大家学习图片处理有帮助!

主要使用到的是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<<24|red<<16|green<<8|blue;//进行标准ARGB输出以实现图象过滤

}

}

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有  導航