在java的GUI上放置图片,并在图片上输出半透明文字
(2007-04-05 23:10:06)
问此问题的人也不少,把以前做的代码拿出来整理为文档,希望对大家学习图片处理有帮助!主要使用到的是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输出以实现图象过滤}}
文章引用自:http://locoy.kalvin.cn
分享:
喜欢
0
赠金笔
加载中,请稍候......
评论加载中,请稍候...
发评论
登录名: 密码: 找回密码 注册记住登录状态
昵 称:
评论并转载此博文
发评论
以上网友发言只代表其个人观点,不代表新浪网的观点或立场。