- public class ScalrConfig {
- //图片质量
- private Float quality = 1F;
- //图片高度
- private int height = 600;
- //图片宽度
- private int width = 600;
- //使长或宽适应到某一个长度
- private Integer size ;
- //重写format
- private ImageExtensionEnum type = ImageExtensionEnum.JPG;
- //是否重写
- private boolean retype = true;
- //保持横纵比
- private boolean aspectRatio = true;
- //压缩过滤
- private ScalrFilter filter;
- public ScalrConfig(int size,int allowWidth,
- int allowHeight){
- this.size = size;
- this.filter = new DefautlScalrFiter(allowWidth,allowHeight);
- }
- public ScalrConfig(int width,int height,
- int allowWidth,int allowHeight){
- this.height = height;
- this.width = width;
- this.filter = new DefautlScalrFiter(allowWidth,allowHeight);
- }
- class DefautlScalrFiter implements ScalrFilter{
- private int allowWidth;
- private int allowHeight;
- @Override
- public boolean doFilter(int _width, int _height) {
- return allowWidth < _width || allowHeight < _height;
- }
- public DefautlScalrFiter(int allowWidth, int allowHeight) {
- this.allowWidth = allowWidth;
- this.allowHeight = allowHeight;
- }
- }
- //省略setter、getter
ImageExtensionEnum
用来定义图片格式(GIF不支持。。。。)
- public enum ImageExtensionEnum {
- JPG,JPEG,PNG,BMP,GIF;
- public final static String [] getExtensions(){
- ImageExtensionEnum enums [] = ImageExtensionEnum.values();
- String [] extensions = new String [enums.length];
- for(int i=0;i<enums.length;i++)
- extensions[i] = enums[i].name();
- return extensions;
- }
- public static boolean isJPG(String extension){
- return JPEG.name().equalsIgnoreCase(extension) ||
- JPG.name().equalsIgnoreCase(extension);
- }
- public static boolean isSameType(String extension1,String extension2){
- if(extension1 == null || extension2 == null) return false;
- return (extension1.equalsIgnoreCase(extension2))||
- (isJPG(extension1)&&isJPG(extension2))?true : false;
- }
- }
ScalrFilter
用来控制图片是否需要被压缩,如果图片过小,此时缩放是不明智的。
下面是图片压缩:
- public interface ScalrFilter {
- public boolean doFilter(int _width,int _height);
- }
- public interface Thumbnailer {
- /**
- *
- * @param is 图片文件流
- * @param size 图片大小
- * @param config 配置
- * @param extension 图片后缀
- * @return
- * @throws Exception
- */
- List<ThumbnailResult> createThumbnails(File file,
- ScalrConfig...configs) throws Exception;
- }
thumnailResult
是一个接口,用来控制缩放成文件、写入输出流、返回缩放后的图片类型和大小:
最后读取、判断文件:
- public interface ThumbnailResult {
- File writeToFile(File destFile) throws Exception;
- void writeToStream(OutputStream stream) throws Exception;
- int getWidth() throws Exception;
- int getHeight() throws Exception;
- String getExtension();
- }
- public abstract class AbstractThumbaniler implements Thumbnailer{
- @Override
- public List<ThumbnailResult> createThumbnails(File file,
- ScalrConfig... configs) throws Exception {
- if(configs == null || configs.length == 0)
- {
- throw new IllegalArgumentException("必须指定一个 ScalrConfig");
- }
- if (file == null)
- {
- throw new IllegalArgumentException("文件不能为空");
- }
- if (!file.exists())
- {
- throw new IllegalArgumentException(file.getAbsolutePath() + "不存在");
- }
- String oldExtension = MyStringUtils.getFilenameExtension(file.getName());
- if(!isSupportedOutputFormat(oldExtension))
- {
- throw new IllegalArgumentException("文件不符合格式");
- }
- BufferedImage image = ImageIO.read(file);
- if (image == null)
- {
- throw new IllegalArgumentException("文件不是一个真正的图片");
- }
- List<ThumbnailResult> results = new ArrayList<ThumbnailResult>();
- for(ScalrConfig config : configs)
- {
- ScalrFilter filter = config.getFilter();
- if(filter == null || (filter != null &&
- filter.doFilter(image.getWidth(), image.getHeight())))
- {
- results.add(createThumbnail(image, config,oldExtension));
- }
- }
- return results;
- }
- abstract ThumbnailResult createThumbnail(BufferedImage image,
- ScalrConfig config,String oldExtension) throws Exception;
- protected List<String> getSupportedOutputFormats(){
- String[] formats = ImageIO.getWriterFormatNames();
- if (formats == null)
- {
- return Collections.emptyList();
- }
- else
- {
- return Arrays.asList(formats);
- }
- }
- private boolean isSupportedOutputFormat(String format){
- for (String supportedFormat : getSupportedOutputFormats())
- {
- if (supportedFormat.equals(format))
- {
- return true;
- }
- }
- return false;
- }
- }
thumbnailator
,它的使用非常简单!
下面是具体的使用:
- Thumbnails.of(new File("q:/user.bmp")).scale(0.25F).toFile(new File("q:/dest.bmmp"));
- Thumbnails.of(new File("q:/user.bmp")).size(300, 300).toFile(new File("q:/dest.bmmp"));
- Thumbnails.of(new File("q:/user.bmp")).size(300,300).
- keepAspectRatio(false).toFile(newFile("q:/dest.bmmp"));
- public class CoobirdThumbnailer extends AbstractThumbaniler {
- @Override
- ThumbnailResult createThumbnail(BufferedImage image, ScalrConfig config,
- String oldExtension)throws Exception {
- int width = image.getWidth();
- int height = image.getHeight();
- this.calc(config, width, height);
- final Builder<BufferedImage> builder = Thumbnails.of(image);
- builder.size(config.getWidth(), config.getHeight())
- .keepAspectRatio(config.getAspectRatio());
- if (config.isRetype())
- {
- String newExtension = config.getType().name();
- if (!ImageExtensionEnum.isSameType(newExtension, oldExtension))
- oldExtension = newExtension;
- }
- builder.outputFormat(oldExtension);
- if (ImageExtensionEnum.isJPG(oldExtension)
- && config.getQuality() != null)
- {
- builder.outputQuality(config.getQuality());
- }
- return new CoobirdThumbnailResult(builder, oldExtension);
- }
- private ScalrConfig calc(ScalrConfig config, int _width, int _height) {
- Integer size = config.getSize();
- if (size != null) {
- config.setAspectRatio(false);
- double sourceRatio = (double) _width / (double) _height;
- if (_width >= _height)
- {
- config.setWidth(size);
- config.setHeight((int) Math.round(size / sourceRatio));
- }
- if (_width < _height)
- {
- config.setHeight(size);
- config.setWidth((int) Math.round(size * sourceRatio));
- }
- }
- return config;
- }
- private final class CoobirdThumbnailResult implements ThumbnailResult {
- private Builder<BufferedImage> builder;
- private String extension;
- private CoobirdThumbnailResult(Builder<BufferedImage> builder,
- String extension) {
- super();
- this.builder = builder;
- this.extension = extension;
- }
- @Override
- public File writeToFile(File destFile) throws Exception {
- String fileName = destFile.getName();
- String _extension = MyStringUtils.getFilenameExtension(fileName);
- if (!extension.equalsIgnoreCase(_extension))
- {
- destFile = new File(destFile.getParent(), fileName.concat(".")
- .concat(extension));
- }
- builder.toFile(destFile);
- return destFile;
- }
- @Override
- public void writeToStream(OutputStream stream) throws Exception {
- builder.toOutputStream(stream);
- }
- @Override
- public int getWidth() throws IOException {
- return builder.asBufferedImage().getWidth();
- }
- @Override
- public int getHeight() throws IOException {
- return builder.asBufferedImage().getHeight();
- }
- @Override
- public String getExtension() {
- return extension;
- }
- }
- }
org.imgscalr.AsyncScalr
具体使用:
- BufferedImage thumbnail =
- Scalr.resize(image, Scalr.Method.SPEED, Scalr.Mode.FIT_TO_WIDTH,
- 150, 100, Scalr.OP_ANTIALIAS);
ImageUtils用来讲BufferedImage输出到文件或者流,具体如下(来源于Thumbanailator的util):
- public class ImageScalrThumbnailer extends AbstractThumbaniler{
- @Override
- ThumbnailResult createThumbnail(BufferedImage image, ScalrConfig config,
- String oldExtension) throws Exception {
- Integer size = config.getSize();
- if(size != null)
- {
- image = Scalr.resize(image, Method.QUALITY, size);
- }
- else
- {
- if(!config.getAspectRatio())
- {
- image = Scalr.resize(image, Method.QUALITY,
- Mode.FIT_EXACT,config.getWidth(),config.getHeight());
- }
- else
- {
- image = Scalr.resize(image, Method.QUALITY,
- config.getWidth(),config.getHeight());
- }
- }
- if (config.isRetype())
- {
- String newExtension = config.getType().name();
- if (!ImageExtensionEnum.isSameType(newExtension, oldExtension))
- oldExtension = newExtension;
- }
- return new ImgScalrThumbnailResult(oldExtension,
- config.getQuality(),image);
- }
- private final class ImgScalrThumbnailResult implements ThumbnailResult{
- private String extension ;
- private Float quality;
- private BufferedImage image;
- @Override
- public File writeToFile(File destFile) throws Exception {
- String filename = destFile.getName();
- String targetExtension = MyStringUtils.getFilenameExtension(filename);
- if(!ImageExtensionEnum.isSameType(extension, targetExtension))
- {
- destFile = new File(destFile.getParent(),
- filename.concat(".").concat(extension));
- }
- ImageUtils.write(image, extension, quality, destFile);
- return destFile;
- }
- @Override
- public void writeToStream(OutputStream stream) throws Exception {
- ImageUtils.write(image, extension, quality, stream);
- }
- @Override
- public int getWidth() {
- return image.getWidth();
- }
- @Override
- public int getHeight() {
- return image.getHeight();
- }
- @Override
- public String getExtension(){
- return extension;
- }
- private ImgScalrThumbnailResult(String extension, Float quality,
- BufferedImage image) {
- this.extension = extension;
- this.quality = quality;
- this.image = image;
- }
- }
- }
MyStringUitls主要用来获取文件后缀名:
- public final class ImageUtils {
- public static void write(BufferedImage img , String formatName,
- Float quality,File destFile) throws IOException{
- Iterator<ImageWriter> writers =
- ImageIO.getImageWritersByFormatName(formatName);
- if (!writers.hasNext())
- {
- throw new UnsupportedFormatException(
- formatName,
- "No suitable ImageWriter found for " + formatName + "."
- );
- }
- ImageWriter writer = writers.next();
- ImageWriteParam writeParam = writer.getDefaultWriteParam();
- if (writeParam.canWriteCompressed())
- {
- writeParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
- List<String> supportedFormats =
- ThumbnailatorUtils.getSupportedOutputFormatTypes(formatName);
- if (!supportedFormats.isEmpty())
- {
- writeParam.setCompressionType(supportedFormats.get(0));
- }
- if(quality != null)
- {
- writeParam.setCompressionQuality(quality);
- }
- }
- ImageOutputStream ios;
- FileOutputStream fos;
- fos = new FileOutputStream(destFile);
- ios = ImageIO.createImageOutputStream(fos);
- if (ios == null || fos == null)
- {
- throw new IOException("Could not open output file.");
- }
- if (
- formatName.equalsIgnoreCase("jpg")
- || formatName.equalsIgnoreCase("jpeg")
- || formatName.equalsIgnoreCase("bmp")
- )
- {
- int width = img.getWidth();
- int height = img.getHeight();
- BufferedImage newImage = new BufferedImage(width, height,
- BufferedImage.TYPE_INT_RGB);
- Graphics g = newImage.createGraphics();
- g.drawImage(img, 0, 0, null);
- g.dispose();
- img = newImage;
- }
- writer.setOutput(ios);
- writer.write(null, new IIOImage(img, null, null), writeParam);
- writer.dispose();
- ios.close();
- fos.close();
- }
- public static void write(BufferedImage img,String formatName,
- Float quality,OutputStream os) throws IOException{
- Iterator<ImageWriter> writers =
- ImageIO.getImageWritersByFormatName(formatName);
- if (!writers.hasNext())
- {
- throw new UnsupportedFormatException(
- formatName,
- "No suitable ImageWriter found for " + formatName + "."
- );
- }
- ImageWriter writer = writers.next();
- ImageWriteParam writeParam = writer.getDefaultWriteParam();
- if (writeParam.canWriteCompressed())
- {
- writeParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
- List<String> supportedFormats =
- ThumbnailatorUtils.getSupportedOutputFormatTypes(formatName);
- if (!supportedFormats.isEmpty())
- {
- writeParam.setCompressionType(supportedFormats.get(0));
- }
- if (quality != null)
- {
- writeParam.setCompressionQuality(quality);
- }
- }
- ImageOutputStream ios = ImageIO.createImageOutputStream(os);
- if (ios == null)
- {
- throw new IOException("Could not open OutputStream.");
- }
- if (
- formatName.equalsIgnoreCase("jpg")
- || formatName.equalsIgnoreCase("jpeg")
- || formatName.equalsIgnoreCase("bmp")
- )
- {
- int width = img.getWidth();
- int height = img.getHeight();
- BufferedImage newImage = new BufferedImage(width, height,
- BufferedImage.TYPE_INT_RGB);
- Graphics g = newImage.createGraphics();
- g.drawImage(img, 0, 0, null);
- g.dispose();
- img = newImage;
- }
- writer.setOutput(ios);
- writer.write(null, new IIOImage(img, null, null), writeParam);
- writer.dispose();
- ios.close();
- }
- }
- public class MyStringUtils {
- private static final char EXTENSION_SEPARATOR = '.';
- private static final String FOLDER_SEPARATOR = "/";
- public static String getFilenameExtension(String path) {
- if (path == null) {
- return null;
- }
- int extIndex = path.lastIndexOf(EXTENSION_SEPARATOR);
- if (extIndex == -1) {
- return null;
- }
- int folderIndex = path.lastIndexOf(FOLDER_SEPARATOR);
- if (folderIndex > extIndex) {
- return null;
- }
- return path.substring(extIndex + 1);
- }
- }
测试:
- public class Test {
- public static void main(String [] args) throws Exception{
- Thumbnailer thumbnailer = ThumbnailerFactory.getThumbnailer();
- File toThumbnail = new File("q:/user.bmp");
- ScalrConfig config = new ScalrConfig(104,105, 160,160);
- config.setAspectRatio(true);
- config.setQuality(1F);
- config.setType(ImageExtensionEnum.BMP);
- List<ThumbnailResult> results = thumbnailer.
- createThumbnails(toThumbnail, config);
- if(!results.isEmpty())
- {
- File destFile = new File("q:/target22222.bmp");
- ThumbnailResult result = results.get(0);
- result.writeToFile(destFile);
- }
- }
- }