缩略图的生成与添加水印

1 缩略图的生成  

 在目前很多的相片网页中,图片容量越大打开网页的速度就越慢,为了解决这个问题,我们可以根据大图生成小图,具体方法如下:

public static void createSmallPhoto(String photoPath, String smallPath) {
File _file = new File(photoPath); // 读入文件
Image src;
try {
src = javax.imageio.ImageIO.read(_file);
int wideth = 110; 
int height = 80; 
BufferedImage tag = new BufferedImage(wideth, height,
BufferedImage.TYPE_INT_RGB);
tag.getGraphics().drawImage(src, 0, 0, wideth, height, null); // 绘制缩小后的图
FileOutputStream out = new FileOutputStream(smallPath); // 输出到文件流
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
encoder.encode(tag); // 近JPEG编码
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}

在上面的代码中,参数photoPath表示大图的地址,参数smallPath表示生成缩略图的地址。在该方法中,首先将photoPath参数转换成Image对象src,够着目标文件tag,设置tag的长度和宽度,对tag进行编码,输出到文件流out,最后关闭文件流。、

在进行图片处理时,还有一些问题需要说明:

    目前只能支持 JPG(JPEG)、GIF和PNG 3种格式 

    对于原图的容量是有限制的,最后不要超过1MB,否则会抛出内存不足的错误.

2 水印效果
  给相片加水印就是在图片上添加文字,添加文字的作用就是最大限度地防止盗用,同时也起到标识图片的作用。该方法的具体实现如下:

public static boolean createMark(String filePath, String printPath,
String markContent) {
ImageIcon imgIcon = new ImageIcon(filePath);//读取相片内容
Image theImg = imgIcon.getImage();  //获取相片的信息
int width = theImg.getWidth(null); //获取相片的宽度
int height = theImg.getHeight(null); //获取相片的长度
BufferedImage bimage = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
Graphics2D g = bimage.createGraphics();
g.setColor(Color.red);
g.drawImage(theImg, 0, 0, null);
Font font = new Font(markContent, Font.BOLD, 200);
g.setFont(font);
g.setComposite(AlphaComposite
.getInstance(AlphaComposite.SRC_OVER, 0.5f));// 50%透明
g.rotate(0.3f); // 文字的旋转角度
g.drawString(markContent, width / 3, height / 3);// 绘制水印的位置
g.dispose();
try {  //通过输出流生成图片内容
FileOutputStream out = new FileOutputStream(printPath);
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bimage);
param.setQuality(100f, true);
encoder.encode(bimage, param);
out.close();
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}

代码流程如下:

1 参数filePath表示原图的路径,参数printPath表示生成水印图片的路径,参数markContent表示加入水印文字的内容

2 根据源相片的路径filePath获取相片的对象,根据根据这个对象获取原图片的长度和宽度

3 根据原图片的长度和宽度,生成RGB类型的图片的相片缓存对象bimage

4 设置水印文字的效果,红色字,透明度50%及文字的倾斜度30度

5 通过输出流对象生成图片内容.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值