如何在Java中创建JPEG的缩略图?

时间:2020-12-30 21:21:19

Can someone please help with some code for creating a thumbnail for a JPEG in Java.

有人能帮我写一些代码来创建Java JPEG的缩略图吗?

I'm new at this, so a step by step explanation would be appreciated.

我是新来的,所以一步一步地解释一下就可以了。

12 个解决方案

#1


63  

Image img = ImageIO.read(new File("test.jpg")).getScaledInstance(100, 100, BufferedImage.SCALE_SMOOTH);

This will create a 100x100 pixels thumbnail as an Image object. If you want to write it back to disk simply convert the code to this:

这将创建一个100x100像素的缩略图作为一个图像对象。如果您想将它写回磁盘,只需将代码转换为以下内容:

BufferedImage img = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB);
img.createGraphics().drawImage(ImageIO.read(new File("test.jpg")).getScaledInstance(100, 100, Image.SCALE_SMOOTH),0,0,null);
ImageIO.write(img, "jpg", new File("test_thumb.jpg"));

Also if you are concerned about speed issues (the method described above is rather slow if you want to scale many images) use these methods and the following declaration :

此外,如果您担心速度问题(如果您想缩放许多图像,上面描述的方法是相当慢的),请使用这些方法和以下声明:

private BufferedImage scale(BufferedImage source,double ratio) {
  int w = (int) (source.getWidth() * ratio);
  int h = (int) (source.getHeight() * ratio);
  BufferedImage bi = getCompatibleImage(w, h);
  Graphics2D g2d = bi.createGraphics();
  double xScale = (double) w / source.getWidth();
  double yScale = (double) h / source.getHeight();
  AffineTransform at = AffineTransform.getScaleInstance(xScale,yScale);
  g2d.drawRenderedImage(source, at);
  g2d.dispose();
  return bi;
}

private BufferedImage getCompatibleImage(int w, int h) {
  GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
  GraphicsDevice gd = ge.getDefaultScreenDevice();
  GraphicsConfiguration gc = gd.getDefaultConfiguration();
  BufferedImage image = gc.createCompatibleImage(w, h);
  return image;
}

And then call :

然后调用:

BufferedImage scaled = scale(img,0.5);

where 0.5 is the scale ratio and img is a BufferedImage containing the normal-sized image.

其中0.5为比例,img为包含正常大小图像的BufferedImage。

#2


30  

As you might have found out "easy" and "good looking result" are two very different things. I have encapsulated both of these requirements into a very simple java image scaling library (Apache 2 license) that just does everything right for you.

你可能已经发现“容易”和“好看”是两个完全不同的东西。我已经将这两个需求封装到一个非常简单的java映像扩展库(Apache 2许可证)中,该库可以为您做所有正确的事情。

Example code to create a thumbnail looks like this:

创建缩略图的示例代码如下:

BufferedImage img = ImageIO.read(...); // load image
BufferedImage scaledImg = Scalr.resize(img, 150);

Your image proportions are honored, the library makes a best-guess at the method it should use based on the amount of change in the image due to scaling (FASTEST, BALANCED or QUALITY) and the best supported Java2D image types are always used to do the scaling to avoid the issue of "black" results or really terrible looking output (e.g. overly dithered GIF images).

你的图像比例是荣幸,图书馆会揣测在方法应该使用基于图像的数量变化由于缩放(最快、平衡和质量)和最好的支持总是使用Java2D图像类型进行扩展,以避免“黑色”的问题看上去非常可怕的结果或输出(如过于犹豫GIF图像)。

Also, if you want to force it to output the best looking thumbnail possible in Java, the API call would look like this:

此外,如果您想强制它输出Java中看起来最好的缩略图,那么API调用应该如下所示:

BufferedImage img = ImageIO.read(...); // load image
BufferedImage scaledImg = Scalr.resize(img, Method.QUALITY, 
                                       150, 100, Scalr.OP_ANTIALIAS);

Not only will the library use the Java2D recommended incremental scaling for you to give you the best looking result, it will also apply an optional antialiasing effect to the thumbnail (ConvolveOp with a very fine-tuned kernel) to every-so-slightly soften the transitions between pixel values so make the thumbnail look more uniform and not sharp or poppy as you might have seen when you go from very large images down to very small ones.

不仅将图书馆使用Java2D推荐增量扩展你给你最好的结果,它还将一个可选的抗锯齿效果应用到缩略图(ConvolveOp非常调整内核)every-so-slightly软化像素值之间的转换,所以让缩略图看起来更统一,而不是大幅或罂粟如你所看到的,当你从非常大的图片非常小的。

You can read through all the comments in the library (the code itself is doc'ed heavily) to see all the different JDK bugs that are worked around or optimizations that are made to improve the performance or memory usage. I spent a LOT of time tuning this implementation and have had a lot of good feedback from folks deploying it in web apps and other Java projects.

您可以通读库中的所有注释(代码本身是文档化的),以查看所有不同的JDK bug,这些bug都是围绕着改进性能或内存使用而进行的优化。我花了很多时间来调优这个实现,并且从在web应用程序和其他Java项目中部署它的人们那里得到了很多很好的反馈。

#3


12  

This is simple way of creating a 100 X 100 thumbnail without any stretch or skew in image.

这是创建一个100 X 100缩略图的简单方法,不会在图像中出现任何拉伸或倾斜。

private  void saveScaledImage(String filePath,String outputFile){
    try {

        BufferedImage sourceImage = ImageIO.read(new File(filePath));
        int width = sourceImage.getWidth();
        int height = sourceImage.getHeight();

        if(width>height){
            float extraSize=    height-100;
            float percentHight = (extraSize/height)*100;
            float percentWidth = width - ((width/100)*percentHight);
            BufferedImage img = new BufferedImage((int)percentWidth, 100, BufferedImage.TYPE_INT_RGB);
            Image scaledImage = sourceImage.getScaledInstance((int)percentWidth, 100, Image.SCALE_SMOOTH);
            img.createGraphics().drawImage(scaledImage, 0, 0, null);
            BufferedImage img2 = new BufferedImage(100, 100 ,BufferedImage.TYPE_INT_RGB);
            img2 = img.getSubimage((int)((percentWidth-100)/2), 0, 100, 100);

            ImageIO.write(img2, "jpg", new File(outputFile));    
        }else{
            float extraSize=    width-100;
            float percentWidth = (extraSize/width)*100;
            float  percentHight = height - ((height/100)*percentWidth);
            BufferedImage img = new BufferedImage(100, (int)percentHight, BufferedImage.TYPE_INT_RGB);
            Image scaledImage = sourceImage.getScaledInstance(100,(int)percentHight, Image.SCALE_SMOOTH);
            img.createGraphics().drawImage(scaledImage, 0, 0, null);
            BufferedImage img2 = new BufferedImage(100, 100 ,BufferedImage.TYPE_INT_RGB);
            img2 = img.getSubimage(0, (int)((percentHight-100)/2), 100, 100);

            ImageIO.write(img2, "jpg", new File(outputFile));
        }

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

#4


4  

The JMagick library (and implementation of ImageMagick in Java) will have what you need.

JMagick库(以及在Java中实现ImageMagick)将具有您所需要的内容。

#5


3  

the Java code above (with the scale / getCompatibleImage methods) worked great for me, but when I deployed to a server, it stopped working, because the server had no display associated with it -- anyone else with this problem can fix it by using: BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);

上面的Java代码(规模/ getCompatibleImage方法)为我伟大的工作,但当我部署到服务器时,它停止工作,因为与它相关联的服务器没有显示,任何人都有这个问题可以通过使用:修复它BufferedImage bi = new BufferedImage(w h BufferedImage.TYPE_INT_RGB);

instead of BufferedImage bi = getCompatibleImage(w, h);

而不是BufferedImage bi = getCompatibleImage(w, h);

and deleting the getCompatibleImage method

删除getCompatibleImage方法

(later note -- it turns out this works great for most images, but I got a bunch from my companys marketing department that are 32 bit color depth jpeg images, and the library throws an unsupported image format exception for all of those :( -- imagemagick / jmagick are starting to look more appealing)

(后来注意——原来这工作对于大多数图像,但是我有一些从我公司市场部32位颜色深度jpeg图像,和图书馆抛出一个不支持的图片格式为所有这些例外:(——imagemagick / jmagick开始看起来更有吸引力)

#6


1  

I have created a application called fotovault (sourceforge.net) which can upload images and create thumbnails in java using imagej apis.

我创建了一个名为fotovault (sourceforge.net)的应用程序,它可以使用imagej api在java中上传图片并创建缩略图。

Please read my blog below

请阅读我的博客

http://www.gingercart.com/Home/java-snippets/create-image-thumbnail-in-java-using-imagej-api

http://www.gingercart.com/Home/java-snippets/create-image-thumbnail-in-java-using-imagej-api

#7


1  

I have gone through a blog according to which you have following options -

我浏览了一个博客,你有以下选择

  1. For simple RGB files use ImageScalr . ImageIO class is used for reading files and ImageScalr to create thumbnails
  2. 对于简单的RGB文件,使用ImageScalr。ImageIO类用于读取文件和创建缩略图
  3. For supporting RGB + CYMK, use ImageIO and JAI (Java Advanced Imaging) API for reading files and ImageScalr to create thumbnail.
  4. 对于支持RGB + CYMK,使用ImageIO和JAI (Java Advanced Imaging) API读取文件,使用ImageScalr创建缩略图。
  5. In case you don’t know what file formats, color mode you are going to deal with, safest option is to use ImageMagick.
  6. 如果你不知道什么文件格式,你要处理的颜色模式,最安全的选择是使用ImageMagick。

Here is link that gives a complete answer with code snippets.

这里是链接,给出了完整的答案和代码片段。

#8


1  

I've used Thumbnailator! It solved my problem with two lines of code.

我使用Thumbnailator !它用两行代码解决了我的问题。

https://github.com/coobird/thumbnailator

https://github.com/coobird/thumbnailator

#9


1  

There are many image processing frameworks available that you can do this with just a few lines. The example below generates the thumbnails in different resolutions (given a width as reference) using Marvin Framework. The three thumbnails were generated in 92 ms.

有许多可用的图像处理框架,只需要几行就可以做到这一点。下面的示例使用Marvin框架生成不同分辨率的缩略图(给定宽度作为参考)。这三个缩略图是在92毫秒内生成的。

input:

输入:

如何在Java中创建JPEG的缩略图?

output:

输出:

如何在Java中创建JPEG的缩略图?

如何在Java中创建JPEG的缩略图?

如何在Java中创建JPEG的缩略图?

import static marvin.MarvinPluginCollection.*;

MarvinImage image = MarvinImageIO.loadImage("./res/input.jpg");
MarvinImage scaledImage = new MarvinImage(1,1);

scale(image, scaledImage, 250);
MarvinImageIO.saveImage(scaledImage, "./res/output_x250.jpg");

scale(image, scaledImage, 150);
MarvinImageIO.saveImage(scaledImage, "./res/output_x150.jpg");

scale(image, scaledImage, 50);
MarvinImageIO.saveImage(scaledImage, "./res/output_x50.jpg");

#10


1  

Simple way to create a thumbnail without stretching or a library. Works with transparency in pngs, too.

简单的方法来创建一个缩略图而不拉伸或图书馆。在png中也使用透明度。

public File createThumbnail(String imageUrl, String targetPath) {
    final int imageSize = 100;
    File thumbnail = new File(targetPath);

    try {
        thumbnail.getParentFile().mkdirs();
        thumbnail.createNewFile();
        BufferedImage sourceImage = ImageIO.read(new File(imageUrl));
        float width = sourceImage.getWidth();
        float height = sourceImage.getHeight();

        BufferedImage img2;
        if (width > height) {
            float scaledWidth = (width / height) * (float) imageSize;
            float scaledHeight = imageSize;

            BufferedImage img = new BufferedImage((int) scaledWidth, (int) scaledHeight, sourceImage.getType());
            Image scaledImage = sourceImage.getScaledInstance((int) scaledWidth, (int) scaledHeight, Image.SCALE_SMOOTH);
            img.createGraphics().drawImage(scaledImage, 0, 0, null);

            int offset = (int) ((scaledWidth - scaledHeight) / 2f);
            img2 = img.getSubimage(offset, 0, imageSize, imageSize);
        }
        else if (width < height) {
            float scaledWidth = imageSize;
            float scaledHeight = (height / width) * (float) imageSize;

            BufferedImage img = new BufferedImage((int) scaledWidth, (int) scaledHeight, sourceImage.getType());
            Image scaledImage = sourceImage.getScaledInstance((int) scaledWidth, (int) scaledHeight, Image.SCALE_SMOOTH);
            img.createGraphics().drawImage(scaledImage, 0, 0, null);

            int offset = (int) ((scaledHeight - scaledWidth) / 2f);
            img2 = img.getSubimage(0, offset, imageSize, imageSize);
        }
        else {
            img2 = new BufferedImage(imageSize, imageSize, sourceImage.getType());
            Image scaledImage = sourceImage.getScaledInstance(imageSize, imageSize, Image.SCALE_SMOOTH);
            img2.createGraphics().drawImage(scaledImage, 0, 0, null);
        }
        ImageIO.write(img2, "png", thumbnail);
    }
    catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return thumbnail;
}

#11


1  

I have writtena util class with static methods years ago using JAI. Java Advanced Imaging API is the most reliable API in Java to deal with images. It's vector interpolation is closest thing to Photoshop in Java world. Here is one of them:

几年前,我使用JAI用静态方法编写了一个writtena util类。Java Advanced Imaging API是Java中最可靠的处理图像的API。矢量插值是Java世界中最接近Photoshop的东西。这是其中之一:

public static ByteArrayOutputStream resize(InputStream inputStream , int IMG_WIDTH,
        int IMG_HEIGHT) throws Exception {
    BufferedImage originalImage = ImageIO.read(inputStream);
    int type = originalImage.getType() == 0 ? BufferedImage.TYPE_INT_ARGB
            : originalImage.getType();
    BufferedImage resizedImage = new BufferedImage(IMG_WIDTH, IMG_HEIGHT,
            type);
    {
        Graphics2D g = resizedImage.createGraphics();
        g.drawImage(originalImage, 0, 0, IMG_WIDTH, IMG_HEIGHT, null);
        g.dispose();
        g.setComposite(AlphaComposite.Src);

        g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        g.setRenderingHint(RenderingHints.KEY_RENDERING,
                RenderingHints.VALUE_RENDER_QUALITY);
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);
    }
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ImageIO.write(resizedImage, "png", bos);
    return bos;

} 

#12


1  

I know this is a pretty old post. I have been looking for a solution to generate the thumbnail so end up using this

我知道这是一个很老的帖子。我一直在寻找一种生成缩略图的解决方案,所以最终使用这个

Thumbnails.of(originalImage).scale(0.25).asBufferedImage();

if you are using for mobile would suggest to set the scale to 0.45

如果你使用移动设备,建议将比例设置为0.45。

Thumbnails.of(originalImage).scale(0.45).asBufferedImage();

https://github.com/coobird/thumbnailator

https://github.com/coobird/thumbnailator

This is certainly much faster using the Graphics2D as have tested the both options.

使用Graphics2D当然要快得多,因为已经对这两个选项进行了测试。

#1


63  

Image img = ImageIO.read(new File("test.jpg")).getScaledInstance(100, 100, BufferedImage.SCALE_SMOOTH);

This will create a 100x100 pixels thumbnail as an Image object. If you want to write it back to disk simply convert the code to this:

这将创建一个100x100像素的缩略图作为一个图像对象。如果您想将它写回磁盘,只需将代码转换为以下内容:

BufferedImage img = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB);
img.createGraphics().drawImage(ImageIO.read(new File("test.jpg")).getScaledInstance(100, 100, Image.SCALE_SMOOTH),0,0,null);
ImageIO.write(img, "jpg", new File("test_thumb.jpg"));

Also if you are concerned about speed issues (the method described above is rather slow if you want to scale many images) use these methods and the following declaration :

此外,如果您担心速度问题(如果您想缩放许多图像,上面描述的方法是相当慢的),请使用这些方法和以下声明:

private BufferedImage scale(BufferedImage source,double ratio) {
  int w = (int) (source.getWidth() * ratio);
  int h = (int) (source.getHeight() * ratio);
  BufferedImage bi = getCompatibleImage(w, h);
  Graphics2D g2d = bi.createGraphics();
  double xScale = (double) w / source.getWidth();
  double yScale = (double) h / source.getHeight();
  AffineTransform at = AffineTransform.getScaleInstance(xScale,yScale);
  g2d.drawRenderedImage(source, at);
  g2d.dispose();
  return bi;
}

private BufferedImage getCompatibleImage(int w, int h) {
  GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
  GraphicsDevice gd = ge.getDefaultScreenDevice();
  GraphicsConfiguration gc = gd.getDefaultConfiguration();
  BufferedImage image = gc.createCompatibleImage(w, h);
  return image;
}

And then call :

然后调用:

BufferedImage scaled = scale(img,0.5);

where 0.5 is the scale ratio and img is a BufferedImage containing the normal-sized image.

其中0.5为比例,img为包含正常大小图像的BufferedImage。

#2


30  

As you might have found out "easy" and "good looking result" are two very different things. I have encapsulated both of these requirements into a very simple java image scaling library (Apache 2 license) that just does everything right for you.

你可能已经发现“容易”和“好看”是两个完全不同的东西。我已经将这两个需求封装到一个非常简单的java映像扩展库(Apache 2许可证)中,该库可以为您做所有正确的事情。

Example code to create a thumbnail looks like this:

创建缩略图的示例代码如下:

BufferedImage img = ImageIO.read(...); // load image
BufferedImage scaledImg = Scalr.resize(img, 150);

Your image proportions are honored, the library makes a best-guess at the method it should use based on the amount of change in the image due to scaling (FASTEST, BALANCED or QUALITY) and the best supported Java2D image types are always used to do the scaling to avoid the issue of "black" results or really terrible looking output (e.g. overly dithered GIF images).

你的图像比例是荣幸,图书馆会揣测在方法应该使用基于图像的数量变化由于缩放(最快、平衡和质量)和最好的支持总是使用Java2D图像类型进行扩展,以避免“黑色”的问题看上去非常可怕的结果或输出(如过于犹豫GIF图像)。

Also, if you want to force it to output the best looking thumbnail possible in Java, the API call would look like this:

此外,如果您想强制它输出Java中看起来最好的缩略图,那么API调用应该如下所示:

BufferedImage img = ImageIO.read(...); // load image
BufferedImage scaledImg = Scalr.resize(img, Method.QUALITY, 
                                       150, 100, Scalr.OP_ANTIALIAS);

Not only will the library use the Java2D recommended incremental scaling for you to give you the best looking result, it will also apply an optional antialiasing effect to the thumbnail (ConvolveOp with a very fine-tuned kernel) to every-so-slightly soften the transitions between pixel values so make the thumbnail look more uniform and not sharp or poppy as you might have seen when you go from very large images down to very small ones.

不仅将图书馆使用Java2D推荐增量扩展你给你最好的结果,它还将一个可选的抗锯齿效果应用到缩略图(ConvolveOp非常调整内核)every-so-slightly软化像素值之间的转换,所以让缩略图看起来更统一,而不是大幅或罂粟如你所看到的,当你从非常大的图片非常小的。

You can read through all the comments in the library (the code itself is doc'ed heavily) to see all the different JDK bugs that are worked around or optimizations that are made to improve the performance or memory usage. I spent a LOT of time tuning this implementation and have had a lot of good feedback from folks deploying it in web apps and other Java projects.

您可以通读库中的所有注释(代码本身是文档化的),以查看所有不同的JDK bug,这些bug都是围绕着改进性能或内存使用而进行的优化。我花了很多时间来调优这个实现,并且从在web应用程序和其他Java项目中部署它的人们那里得到了很多很好的反馈。

#3


12  

This is simple way of creating a 100 X 100 thumbnail without any stretch or skew in image.

这是创建一个100 X 100缩略图的简单方法,不会在图像中出现任何拉伸或倾斜。

private  void saveScaledImage(String filePath,String outputFile){
    try {

        BufferedImage sourceImage = ImageIO.read(new File(filePath));
        int width = sourceImage.getWidth();
        int height = sourceImage.getHeight();

        if(width>height){
            float extraSize=    height-100;
            float percentHight = (extraSize/height)*100;
            float percentWidth = width - ((width/100)*percentHight);
            BufferedImage img = new BufferedImage((int)percentWidth, 100, BufferedImage.TYPE_INT_RGB);
            Image scaledImage = sourceImage.getScaledInstance((int)percentWidth, 100, Image.SCALE_SMOOTH);
            img.createGraphics().drawImage(scaledImage, 0, 0, null);
            BufferedImage img2 = new BufferedImage(100, 100 ,BufferedImage.TYPE_INT_RGB);
            img2 = img.getSubimage((int)((percentWidth-100)/2), 0, 100, 100);

            ImageIO.write(img2, "jpg", new File(outputFile));    
        }else{
            float extraSize=    width-100;
            float percentWidth = (extraSize/width)*100;
            float  percentHight = height - ((height/100)*percentWidth);
            BufferedImage img = new BufferedImage(100, (int)percentHight, BufferedImage.TYPE_INT_RGB);
            Image scaledImage = sourceImage.getScaledInstance(100,(int)percentHight, Image.SCALE_SMOOTH);
            img.createGraphics().drawImage(scaledImage, 0, 0, null);
            BufferedImage img2 = new BufferedImage(100, 100 ,BufferedImage.TYPE_INT_RGB);
            img2 = img.getSubimage(0, (int)((percentHight-100)/2), 100, 100);

            ImageIO.write(img2, "jpg", new File(outputFile));
        }

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

#4


4  

The JMagick library (and implementation of ImageMagick in Java) will have what you need.

JMagick库(以及在Java中实现ImageMagick)将具有您所需要的内容。

#5


3  

the Java code above (with the scale / getCompatibleImage methods) worked great for me, but when I deployed to a server, it stopped working, because the server had no display associated with it -- anyone else with this problem can fix it by using: BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);

上面的Java代码(规模/ getCompatibleImage方法)为我伟大的工作,但当我部署到服务器时,它停止工作,因为与它相关联的服务器没有显示,任何人都有这个问题可以通过使用:修复它BufferedImage bi = new BufferedImage(w h BufferedImage.TYPE_INT_RGB);

instead of BufferedImage bi = getCompatibleImage(w, h);

而不是BufferedImage bi = getCompatibleImage(w, h);

and deleting the getCompatibleImage method

删除getCompatibleImage方法

(later note -- it turns out this works great for most images, but I got a bunch from my companys marketing department that are 32 bit color depth jpeg images, and the library throws an unsupported image format exception for all of those :( -- imagemagick / jmagick are starting to look more appealing)

(后来注意——原来这工作对于大多数图像,但是我有一些从我公司市场部32位颜色深度jpeg图像,和图书馆抛出一个不支持的图片格式为所有这些例外:(——imagemagick / jmagick开始看起来更有吸引力)

#6


1  

I have created a application called fotovault (sourceforge.net) which can upload images and create thumbnails in java using imagej apis.

我创建了一个名为fotovault (sourceforge.net)的应用程序,它可以使用imagej api在java中上传图片并创建缩略图。

Please read my blog below

请阅读我的博客

http://www.gingercart.com/Home/java-snippets/create-image-thumbnail-in-java-using-imagej-api

http://www.gingercart.com/Home/java-snippets/create-image-thumbnail-in-java-using-imagej-api

#7


1  

I have gone through a blog according to which you have following options -

我浏览了一个博客,你有以下选择

  1. For simple RGB files use ImageScalr . ImageIO class is used for reading files and ImageScalr to create thumbnails
  2. 对于简单的RGB文件,使用ImageScalr。ImageIO类用于读取文件和创建缩略图
  3. For supporting RGB + CYMK, use ImageIO and JAI (Java Advanced Imaging) API for reading files and ImageScalr to create thumbnail.
  4. 对于支持RGB + CYMK,使用ImageIO和JAI (Java Advanced Imaging) API读取文件,使用ImageScalr创建缩略图。
  5. In case you don’t know what file formats, color mode you are going to deal with, safest option is to use ImageMagick.
  6. 如果你不知道什么文件格式,你要处理的颜色模式,最安全的选择是使用ImageMagick。

Here is link that gives a complete answer with code snippets.

这里是链接,给出了完整的答案和代码片段。

#8


1  

I've used Thumbnailator! It solved my problem with two lines of code.

我使用Thumbnailator !它用两行代码解决了我的问题。

https://github.com/coobird/thumbnailator

https://github.com/coobird/thumbnailator

#9


1  

There are many image processing frameworks available that you can do this with just a few lines. The example below generates the thumbnails in different resolutions (given a width as reference) using Marvin Framework. The three thumbnails were generated in 92 ms.

有许多可用的图像处理框架,只需要几行就可以做到这一点。下面的示例使用Marvin框架生成不同分辨率的缩略图(给定宽度作为参考)。这三个缩略图是在92毫秒内生成的。

input:

输入:

如何在Java中创建JPEG的缩略图?

output:

输出:

如何在Java中创建JPEG的缩略图?

如何在Java中创建JPEG的缩略图?

如何在Java中创建JPEG的缩略图?

import static marvin.MarvinPluginCollection.*;

MarvinImage image = MarvinImageIO.loadImage("./res/input.jpg");
MarvinImage scaledImage = new MarvinImage(1,1);

scale(image, scaledImage, 250);
MarvinImageIO.saveImage(scaledImage, "./res/output_x250.jpg");

scale(image, scaledImage, 150);
MarvinImageIO.saveImage(scaledImage, "./res/output_x150.jpg");

scale(image, scaledImage, 50);
MarvinImageIO.saveImage(scaledImage, "./res/output_x50.jpg");

#10


1  

Simple way to create a thumbnail without stretching or a library. Works with transparency in pngs, too.

简单的方法来创建一个缩略图而不拉伸或图书馆。在png中也使用透明度。

public File createThumbnail(String imageUrl, String targetPath) {
    final int imageSize = 100;
    File thumbnail = new File(targetPath);

    try {
        thumbnail.getParentFile().mkdirs();
        thumbnail.createNewFile();
        BufferedImage sourceImage = ImageIO.read(new File(imageUrl));
        float width = sourceImage.getWidth();
        float height = sourceImage.getHeight();

        BufferedImage img2;
        if (width > height) {
            float scaledWidth = (width / height) * (float) imageSize;
            float scaledHeight = imageSize;

            BufferedImage img = new BufferedImage((int) scaledWidth, (int) scaledHeight, sourceImage.getType());
            Image scaledImage = sourceImage.getScaledInstance((int) scaledWidth, (int) scaledHeight, Image.SCALE_SMOOTH);
            img.createGraphics().drawImage(scaledImage, 0, 0, null);

            int offset = (int) ((scaledWidth - scaledHeight) / 2f);
            img2 = img.getSubimage(offset, 0, imageSize, imageSize);
        }
        else if (width < height) {
            float scaledWidth = imageSize;
            float scaledHeight = (height / width) * (float) imageSize;

            BufferedImage img = new BufferedImage((int) scaledWidth, (int) scaledHeight, sourceImage.getType());
            Image scaledImage = sourceImage.getScaledInstance((int) scaledWidth, (int) scaledHeight, Image.SCALE_SMOOTH);
            img.createGraphics().drawImage(scaledImage, 0, 0, null);

            int offset = (int) ((scaledHeight - scaledWidth) / 2f);
            img2 = img.getSubimage(0, offset, imageSize, imageSize);
        }
        else {
            img2 = new BufferedImage(imageSize, imageSize, sourceImage.getType());
            Image scaledImage = sourceImage.getScaledInstance(imageSize, imageSize, Image.SCALE_SMOOTH);
            img2.createGraphics().drawImage(scaledImage, 0, 0, null);
        }
        ImageIO.write(img2, "png", thumbnail);
    }
    catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return thumbnail;
}

#11


1  

I have writtena util class with static methods years ago using JAI. Java Advanced Imaging API is the most reliable API in Java to deal with images. It's vector interpolation is closest thing to Photoshop in Java world. Here is one of them:

几年前,我使用JAI用静态方法编写了一个writtena util类。Java Advanced Imaging API是Java中最可靠的处理图像的API。矢量插值是Java世界中最接近Photoshop的东西。这是其中之一:

public static ByteArrayOutputStream resize(InputStream inputStream , int IMG_WIDTH,
        int IMG_HEIGHT) throws Exception {
    BufferedImage originalImage = ImageIO.read(inputStream);
    int type = originalImage.getType() == 0 ? BufferedImage.TYPE_INT_ARGB
            : originalImage.getType();
    BufferedImage resizedImage = new BufferedImage(IMG_WIDTH, IMG_HEIGHT,
            type);
    {
        Graphics2D g = resizedImage.createGraphics();
        g.drawImage(originalImage, 0, 0, IMG_WIDTH, IMG_HEIGHT, null);
        g.dispose();
        g.setComposite(AlphaComposite.Src);

        g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        g.setRenderingHint(RenderingHints.KEY_RENDERING,
                RenderingHints.VALUE_RENDER_QUALITY);
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);
    }
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ImageIO.write(resizedImage, "png", bos);
    return bos;

} 

#12


1  

I know this is a pretty old post. I have been looking for a solution to generate the thumbnail so end up using this

我知道这是一个很老的帖子。我一直在寻找一种生成缩略图的解决方案,所以最终使用这个

Thumbnails.of(originalImage).scale(0.25).asBufferedImage();

if you are using for mobile would suggest to set the scale to 0.45

如果你使用移动设备,建议将比例设置为0.45。

Thumbnails.of(originalImage).scale(0.45).asBufferedImage();

https://github.com/coobird/thumbnailator

https://github.com/coobird/thumbnailator

This is certainly much faster using the Graphics2D as have tested the both options.

使用Graphics2D当然要快得多,因为已经对这两个选项进行了测试。