`
jarod2008
  • 浏览: 82385 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

java生成文件缩略图

    博客分类:
  • java
阅读更多

转自:http://schmidt.devlib.org/java/save-jpeg-thumbnail.html#source

 

Note: I wrote an article on potential problems when creating thumbnails with Java .

This programm loads an image via java.awt.Toolkit , scales it down to a user-defined resolution and saves it as a JPEG file. The first part, the loading of the original image, is done the same way as in Viewer . So if you don't know yet how loading images with Toolkit works you might want to study that program first.

Different from Viewer , this program (Thumbnail) works on the command line. So you won't get any windows or other graphical user interface components. The only visual feedback is the word Done. after the program successfully terminated.

To use this program do the following:

  • Save the program's source code as Thumbnail.java (regard case).
  • Open a shell (prompt), go to the directory where Thumbnail.java is and compile it:
    javac Thumbnail.java
    You should now have a new class file Thumbnail.class .
  • Run the program with five parameters for image file, thumbnail file, thumbnail width and thumbnail height and quality (a value from 0 to 100, 100 being the best and 0 the worst quality), e.g.:
    java Thumbnail c:\image.jpg c:\thumbnail.jpg 120 80 75
    The file image.jpg must exist already, thumbnail.jpg will be created (and any existing file of that name overwritten).

You will need Java 1.2 or higher to successfully run this program. The com.sun.image.codec.jpeg package that will be used for saving the thumbnail is not available with all Java development kits, but as long as you are using a Sun JDK, it should be present.

With Java 1.4 a new way of writing JPEG files was introduced, the image I/O library in the package javax.imageio . See the Screenshot.java example program . It saves as PNG, but all you have to do is change the second argument of ImageIO.write from png to jpg . The advantage of ImageIO : It is available with each 1.4+ JDK and JRE, not only those coming from Sun.

Explanation

Now let's see how this program works. First, it is checked that we have exactly five arguments. If this is not the case, an error message is printed to output and the program terminates.

Next, the input image is loaded via Toolkit and MediaTracker just as it was done in Viewer .

The third and fourth program argument contain the maximum size of the thumbnail to be created. The actual size of the thumbnail will be computed from that maximum size and the actual size of the image (all sizes are given as pixels). The code that does this is not really very readable, and also not essential to loading and saving image files. But it is necessary to create a thumbnail that is scaled correctly.

As an example, if the two arguments for the maximum thumbnail size are both 100 and the image that was loaded is 400 times 200 pixels large, we want the thumbnail to be 100 times 50 pixels large, not 100 times 100 , because the original image is twice as wide as it is high. A 100 times 100 pixel thumbnail would contain a very skewed version of the original image.

Now that we have determined the size of the thumbnail we create a BufferedImage of that size, named thumbImage . We ask for a Graphics2D object for that new thumbnail image and call its drawImage method to draw the original image on that new image. The call to drawImage does the actual scaling. The rendering hints for bilinear interpolation can be left out (remove the line with graphics2D.setRenderingHint ) if high quality is not required and speed more important. Note that embedded color profiles can make scaling with bilinear interpolation very slow with certain versions of the JDK; this supposedly gets better with JDK 6. If you can't rule out that you are dealing with such JPEGs, make sure to not use the interpolation hint or thumbnail creation will take forever (well, two minutes on a modern system on a 6M image). For nicer results (at least in some cases) try RenderingHints.VALUE_INTERPOLATION_BICUBIC instead of RenderingHints.VALUE_INTERPOLATION_BILINEAR . Same warning as above.

In order to save the scaled-down image to a JPEG file, we create a buffered FileOutputStream with the second argument as name and initialize the necessary objects from the com.sun.image.codec.jpeg package. The quality argument from the command line is converted from the interval 0 to 100 to the interval 0.0f to 1.0f , because that's what the codec expects (I mostly use 0.75f ). The higher that quality number is, the better the resulting thumbnail image quality, but also the larger the resulting file.

The call to System.exit(0); is unfortunately necessary for some Java runtime environments (because of a bug that keeps the AWT thread from terminating).

Source code of Thumbnail.java

import com.sun.image.codec.jpeg.*;
import java.awt.*;
import java.awt.image.*;
import java.io.*;

/**
 * Thumbnail.java (requires Java 1.2+)
 * Load an image, scale it down and save it as a JPEG file.
 * @author Marco Schmidt
 */
public class Thumbnail {
  public static void main(String[] args) throws Exception {
    if (args.length != 5) {
      System.err.println("Usage: java Thumbnail INFILE " +
        "OUTFILE WIDTH HEIGHT QUALITY");
      System.exit(1);
    }
    // load image from INFILE
    Image image = Toolkit.getDefaultToolkit().getImage(args[0]);
    MediaTracker mediaTracker = new MediaTracker(new Container());
    mediaTracker.addImage(image, 0);
    mediaTracker.waitForID(0);
    // determine thumbnail size from WIDTH and HEIGHT
    int thumbWidth = Integer.parseInt(args[2]);
    int thumbHeight = Integer.parseInt(args[3]);
    double thumbRatio = (double)thumbWidth / (double)thumbHeight;
    int imageWidth = image.getWidth(null);
    int imageHeight = image.getHeight(null);
    double imageRatio = (double)imageWidth / (double)imageHeight;
    if (thumbRatio < imageRatio) {
      thumbHeight = (int)(thumbWidth / imageRatio);
    } else {
      thumbWidth = (int)(thumbHeight * imageRatio);
    }
    // draw original image to thumbnail image object and
    // scale it to the new size on-the-fly
    BufferedImage thumbImage = new BufferedImage(thumbWidth, 
      thumbHeight, BufferedImage.TYPE_INT_RGB);
    Graphics2D graphics2D = thumbImage.createGraphics();
    graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
      RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    graphics2D.drawImage(image, 0, 0, thumbWidth, thumbHeight, null);
    // save thumbnail image to OUTFILE
    BufferedOutputStream out = new BufferedOutputStream(new
      FileOutputStream(args[1]));
    JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
    JPEGEncodeParam param = encoder.
      getDefaultJPEGEncodeParam(thumbImage);
    int quality = Integer.parseInt(args[4]);
    quality = Math.max(0, Math.min(quality, 100));
    param.setQuality((float)quality / 100.0f, false);
    encoder.setJPEGEncodeParam(param);
    encoder.encode(thumbImage);
    out.close(); 
    System.out.println("Done.");
    System.exit(0);
  }
}
分享到:
评论

相关推荐

    java 图片生成缩略图

    在本文中,我们将介绍使用Java生成缩略图的方法。 缩略图生成方法 在 Java 中,生成缩略图可以使用多种方法,本文将介绍两种常见的方法。 方法一:使用BufferedImage类 使用BufferedImage类可以实现图片的缩略图...

    java 上传图片生成缩略图

    本文介绍了使用Java实现上传图片并生成缩略图的方法,包括获取文件路径、读取图像、创建缩略图及保存缩略图等步骤。通过这种方式,可以在不损失原图质量的前提下,有效地减少加载时间,提升用户体验。此外,本文还...

    java视频生成图片(缩略图)-实例-(指定时间)

    在Java编程中,生成视频的缩略图是一项常见的任务,特别是在多媒体处理或视频分享平台的开发中。这个实例主要关注如何使用Java在指定的时间点截取视频生成图片。以下是一些相关的知识点: 1. **Java Media ...

    java生成图片缩略图和二进制文件的工具类

    将图片生成缩略图和转换为二进制的工具类,缩略图大小可调

    JAVA获取视频缩略图

    首先,Java本身并不直接支持从视频文件中提取缩略图,但可以通过第三方库如JMF(Java Media Framework)或FFmpeg来实现。不过,JMF已经较为过时,目前更推荐使用FFmpeg库,它是一个强大的多媒体处理工具,提供了跨...

    java生成缩略图

    根据提供的文件信息,我们可以总结出以下关于“Java生成缩略图”的相关知识点: ### Java生成缩略图基础知识 #### 缩略图的概念 缩略图是原始图像的一个较小版本,通常用于网页展示、图片预览等场景。通过生成缩略...

    Java中gif动图缩略图处理jar包

    这个jar包为开发者提供了一个方便的API来处理GIF图像的缩略图生成,使得在Java项目中实现这一功能变得更加简单。 GIF4J库的核心功能包括读取GIF文件、解析其帧信息、调整图像尺寸并重新组合成新的GIF文件。以下是...

    java缩略图代码

    在 Java 中生成图片缩略图是一项常见的需求,这通常涉及到图像处理技术。以下是一个 Java 类 `GetPicture` 的示例,它包含了获取网络图片、截取屏幕以及创建图片缩略图的功能。我们将详细解释其中的关键知识点。 1....

    java批量上传图片并生成缩略图

    总之,实现"java批量上传图片并生成缩略图"的功能,需要结合Java的Servlet技术处理文件上传,使用图像处理库生成缩略图,并且在前后端之间进行有效的通信。这不仅是技术上的挑战,也是对系统设计和优化能力的考验。

    java生成缩略图的方法示例

    Java 生成缩略图的方法示例 Java 生成缩略图是指使用 Java 语言生成缩略图的过程,这个过程中涉及到各种图形处理技巧。下面将详细介绍 Java 生成缩略图的方法示例。 图像处理基础 在 Java 中,图像处理是通过使用...

    java生成缩略图.pdf

    总结来说,生成缩略图的Java代码需要考虑图像的透明度、格式支持以及最终文件的大小和质量。在处理透明图像时,选择支持Alpha通道的格式(如PNG或GIF)至关重要。同时,根据实际需求,可以调整缩略图的尺寸策略,...

    基于Springmvc的上传图片并生成缩略图

    总结来说,基于Springmvc的图片上传和生成缩略图功能涉及以下几个关键步骤:配置Springmvc支持文件上传,编写Controller处理上传请求,生成并保存缩略图,以及与前端交互提供反馈。这些步骤都需要对Springmvc、文件I...

    java利用ffmpeg获取视频缩略图

    2. **构建命令**:在Java程序中,你需要构建一个ffmpeg命令,指定视频文件的路径和输出缩略图的路径。命令通常类似于`ffmpeg -i input.mp4 -ss time -vframes 1 output.png`,其中`-i`参数是输入视频,`-ss`定义了...

    JSP上传图片并生成缩略图

    接下来,一个单独的Java类或方法会处理缩略图的生成,可能是在图片上传后立即执行,也可能是异步处理。 在处理过程中,需要注意几个关键点: 1. **文件验证**:确保上传的文件是图片格式,防止恶意文件上传。 2. **...

    pdfbox,生成pdf文件的缩略图

    在本场景中,我们关注的是PDFBox的一个特定功能:生成PDF文件的缩略图。这有助于在显示文档列表时提供预览,类似于百度文库中对文档的呈现方式,用户可以通过缩略图快速了解文档内容。 生成PDF缩略图的核心概念是...

    Java将web页生成缩略图

    本篇将详细介绍如何利用Java和PhantomJS来生成网页的缩略图。 PhantomJS是一个基于Webkit的无头浏览器,它能够加载网页并执行JavaScript,而且不依赖于任何图形用户界面。这种特性使得PhantomJS非常适合用来生成...

    动态缩略图实现方案

    总的来说,Java提供了强大的图像处理能力,使得在服务器端动态生成缩略图成为可能。通过熟练掌握Java 2D API和其他相关库,开发者可以构建高效、灵活的动态缩略图系统,满足各种应用场景的需求。

    java生成缩略图.zip

    在这个"java生成缩略图.zip"压缩包中,我们可能找到了一份Java源代码,用于演示如何在Java环境下创建图像的缩略图。 首先,我们要了解在Java中生成缩略图的关键概念和技术。Java的`java.awt.image`和`javax.imageio...

    jsp上传图片并生成缩略图

    在Java服务器页面(JSP)中,上传图片并生成缩略图是一项常见的需求,尤其在构建网站或Web应用时。这个过程涉及到多个步骤,包括文件上传、图片处理和存储。以下将详细介绍如何实现这一功能。 1. **文件上传**: -...

    java头像剪上传剪切设置大小,生成固定缩略图大小

    在Java编程语言中,处理图像任务,如头像剪切、上传、设置大小以及生成固定缩略图,是一项常见的需求。这些操作广泛应用于社交媒体、个人资料管理或任何需要用户自定义头像的系统中。本篇文章将深入探讨如何使用Java...

Global site tag (gtag.js) - Google Analytics