目录
代码示例
thumbnailator是一个开源的图片工具包,提供诸如图片缩放、裁剪、旋转、加水印等一些列功能,简单好用
项目地址:https://github.com/coobird/thumbnailator
最新版本为 0.4.8:
<dependency>
<groupId>net.coobird</groupId>
<artifactId>thumbnailator</artifactId>
<version>0.4.8</version>
</dependency>
package com.sean;
import net.coobird.thumbnailator.Thumbnailator;
import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.builders.BufferedImageBuilder;
import net.coobird.thumbnailator.geometry.Position;
import net.coobird.thumbnailator.geometry.Positions;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
/**
* Created by seanzou on 2017/3/31.
*/
public class ImageUtil {
public static void main(String[] args) throws Exception {
File file = new File("d:\\in.jpg");
// 转换图片格式为png
Thumbnails.of(file)
.scale(1)
.outputFormat("png")
.toFile(new File("d:\\out.png"));
// 图片放大2倍,像素由700*1050变为1400*2100
Thumbnails.of(file)
.scale(2)
.toFile(new File("d:\\magnify.jpg"));
// 图片缩小至1/4,像素由700*1050变为175*263
Thumbnails.of(file)
.scale(0.25)
.toFile(new File("d:\\shrink.jpg"));
// 图片剪裁, x y a b,具体含义请参考下面配图
Thumbnails.of(file)
.sourceRegion(100, 100, 550, 550)
.scale(1)
.toFile(new File("d:\\head.jpg"));
// 旋转, 正数顺时针旋转,负数逆时针旋转
Thumbnails.of(file)
.rotate(-90)
.size(400,400)
.keepAspectRatio(false) // 忽略原图比例,强制转换为size设置的像素
.toFile(new File("d:\\rotate.jpg"));
// 创建水印图片
// 后面的两个参数用来校验水印图片的像素,所以必须和水印的像素保持一致
// 否则将会导致水印的添加失败
BufferedImage image = Thumbnailator.createThumbnail(
new File("d:\\wm.jpg"), 300, 300);
// 添加水印
FileInputStream in = new FileInputStream(file);
FileOutputStream out = new FileOutputStream(new File("d:\\watermark.jpg"));
Thumbnails.of(in)
.watermark(Positions.CENTER, image , 0.5f) // 水印位置,水印图片,透明度
.scale(1)
.toOutputStream(out);
}
}

PNG图片透明背景变黑
在说明这个问题之前,需要先了解图片位深的相关知识
位深是指存储每个像素所用的位数,位数越大,可以保存的颜色越多
位深是8位的图,最多只有2的8次幂,也就是256种颜色;当位深达到16位时,支持的颜色就有2的16次幂,65536种颜色,也就是我们说的高彩;当位深达到24位时,支持的颜色就有2的24次幂,16777216种颜色,也就是我们说的真彩;32位是在24位的基础上,多出8位用来保存Alpha通道(透明度)
那么很明显的原因就是,图片在处理的过程中Alpha通道相关信息丢失了,那我们在处理图片时,就要指定图片类型是支持Alpha通道的
Thumbnails.of(file)
.imageType(BufferedImage.TYPE_INT_ARGB)
.outputFormat("jpg")
.scale(0.5)
.outputQuality(0.5)
.toFile(newFile);
看一下TYPE_INT_ARGB的源代码,可以知道这种图片类型是支持Alpha通道的
/**
* Represents an image with 8-bit RGBA color components packed into
* integer pixels. The image has a <code>DirectColorModel</code>
* with alpha. The color data in this image is considered not to be
* premultiplied with alpha. When this type is used as the
* <code>imageType</code> argument to a <code>BufferedImage</code>
* constructor, the created image is consistent with images
* created in the JDK1.1 and earlier releases.
*/
public static final int TYPE_INT_ARGB = 2;
PNG图片压缩后变大
问题产生的原因是:无论原图的位深是多少,处理后的图片位深均为32,因此图片会变大很多
在不改变图片尺寸的前提下,还没找到解决方案,不清楚如何指定处理后的图片位深与原图相同
本文介绍了一个强大的图片处理工具thumbnailator,提供了丰富的图片处理功能,如缩放、裁剪、旋转和加水印等,并通过代码示例展示了其使用方法。同时,文章还探讨了PNG图片在处理过程中可能出现的问题及解决策略。
2206

被折叠的 条评论
为什么被折叠?



