Image相关的数据类型转换和用法

 首先定义用到的数据类型
Icon icon;//声明一个图标类
Image image;
ImageIcon icon;//使用ImageIcon类创建一个图标

BufferedImage bi;
byte[] bytes;
Blob blob;
String fileName;

一、ImageIcon类
构造函数
icon = new ImageIcon(fileName);
icon = new ImageIcon(bytes);
icon = new ImageIcon(image);

实用方法
int getIconHeight();
int getIconWidth();
void setImage(Image image);
Image getImage();

小结
ImageIcon与Image间的转换比较方便,更偏向于应用方面,主要是控件中的setIcon(ImageIcon)方法。


二、Image类
实用方法
1.缩放图片大小,其中hints通常用Image.SCALE_SMOOTH
Image getScaledInstance(int width, int height, int hints);

2.获取图片长宽值
int getHeight(null);
int getWidth(null);

小结
Image更像一个过渡类,将图形转换成别的图形类,如ImageIcon、BufferedImage等。

三、BufferedImage类
构造函数
bi = new BufferedImage(int width, int height, int imageType);
这里的imageType我习惯用BufferedImage.TYPE_INT_ARGB,构造出来的BufferedImage更像是一个模式,需要往里面加数据。

关于BufferedImage的一些用法
1.Image写入BufferedImage
bi.getGraphics().drawImage(Image img, int x, int y, int width, int height, ImageObserver observer)

2.BufferedImage转换到bytes[]或文件
bi = ImageIO.read(new File(fileName));
//放缩到36*36
image= bi.getScaledInstance (36,36,Image.SCALE_SMOOTH);
double wRatio = 36.0/bi.getWidth();
double hRatio = 36.0/bi.getHeight();
//AffineTransformOp.TYPE_BICUBIC 表示3次方放缩
AffineTransformOp op = new AffineTransformOp(AffineTransform.getScaleInstance(wRatio, hRatio),AffineTransformOp.TYPE_BICUBIC);
bi = op.filter(bi, null);
ByteArrayOutputStream out = new ByteArrayOutputStream();
ImageIO.write(bi, "jpg", out);
bytes = out.toByteArray();
这 里用到的ImageIO.write方法参数为(RenderedImage im, String formatName,  ImageOutputStream output),其中参数output是图形的输出流,可以定向到文件流 new FileOutputStream()实现将图象写入到文件。

3.以上两个用法综合使用可以将Image写入到byte[]和文件。

四、byte[]和Blob的转换
图像在MySql中用BLOB数据类型(Binary Large Object)存储

1.byte[]到Blob转换
blob = new SerialBlob(bytes);
blob.setBytes(long pos, byte[] bytes);

2.Blob到byte[]转换
bytes = blob.getBytes(long pos, int length);

这里需要注意的一点是存储图形到MySql数据库时使用Blob类型,从MySql取出图形的Object应转换到byte[]
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值