Thumbnails 图片处理

Thumbnails 是由谷歌提供的图片处理包,目前版本0.4.8。

可以简洁的实现图片的缩放、压缩、旋转、水印、格式转换等操作。

示例代码:

package test;

import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.geometry.Coordinate;
import net.coobird.thumbnailator.geometry.Positions;
import org.junit.Test;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;

public class TestImageUtils {

@Test
public void testThumbnails() throws IOException {
String baseUrl = "imgurl";
String QRCodeUrl = "watermark url";

// 读入图片,输入可以是Url/InputStream/File/BufferedImage
BufferedImage qrCode = Thumbnails.of(new URL(QRCodeUrl)).size(220, 220).asBufferedImage();
Thumbnails.of(new URL(baseUrl))
.size(1080, 1372)
.watermark(new Coordinate(807, 1115), qrCode, 1.0f) //确定水印的起始位置和透明度
.watermark(Positions.BOTTOM_RIGHT, qrCode, 0.5f) //另一种确认水印位置的方式
.toFile("E:/thumbnails.jpg"); //可以输出文件或OutputStream
}
}

 

Thumbnails 不能添加文字,要添加文字的话需要自己另行处理。

示例代码:

package outfox.weixinactivity.weixin.utils;

import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.geometry.Coordinate;import org.junit.Test;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.net.URL;

public class TestImage {  
    @Test
    public void testImageText() throws IOException {
   // 载入图片、加水印 String baseUrl
= "imgurl"; String QRCodeUrl = "watermark url"; ByteArrayOutputStream out = new ByteArrayOutputStream(); BufferedImage qrCode = Thumbnails.of(new URL(QRCodeUrl)).size(220, 220).asBufferedImage(); Thumbnails.of(new URL(baseUrl)) .size(1080, 1372) .watermark(new Coordinate(807, 1115), qrCode, 1.0f) .toOutputStream(out); BufferedImage image = ImageIO.read(new ByteArrayInputStream(out.toByteArray())); // 填加文字 BufferedImage bi = new BufferedImage(1080, 1372, BufferedImage.TYPE_INT_RGB); Graphics2D g = bi.createGraphics(); g.drawImage(image, 0, 0, null); g.setFont(new Font("苹方", Font.PLAIN, 40)); g.setColor(Color.ORANGE); g.drawString("hello!", 220, 100); g.drawString("you", 220, 150); g.dispose(); ImageIO.write(bi, "jpg", new File("E:/testImage.jpg")); } }

 

posted @ 2018-08-01 14:48  风小雅  阅读(4327)  评论(1编辑  收藏  举报