转自: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:
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).
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 上传图片时生成对应的缩略图,缩略图的大小可手动更改,代码中有详细注释
将图片生成缩略图和转换为二进制的工具类,缩略图大小可调
从ueditor中把批量上传图片的flash分离出来,同时实现生成缩略图
很好的java代码,
动态缩略图实现方案,java实现动态缩略图
上传有大小限制,所以工程移除了lib,需要自己下载 javacv jar包下载地址:http://search.maven.org/remotecontent?filepath=org/bytedeco/javacv-platform/1.4.2/javacv-platform-1.4.2-bin.zip
用于将pdf文件生成其缩略图以供显示时使用,很实用的类似于百度文库中的文档里列表的图片一样
java:html生成图片,所有生成方法的优缺点。
Thumbnailator 是一个为Java界面更流畅的缩略图生成库。从API提供现有的图像文件和图像对象的缩略图中简化了缩略过程,且允许微调缩略图生成,同时保持了需要写入到最低限度的代码量。同时还支持根据一个目录批量...
一个 Flutter 插件,用于从本地存储上的视频生成缩略图。 兼容性 仅限安卓操作系统 用法 依赖它 在 pubspec.yaml 文件中添加thumbnails作为依赖项。 thumbnails : ^1.0.1 更新 Android 权限 将这些行添加到 ...
与大家分享一个比较完整的Java图片上传类,这个类主要功能是完成图片上传,另外还支持自动生成和保存缩略图,使用获得当前文件路径的方法,通过当前日期生成文件名,我觉得这个类对于WEB开发应用还是很实用的。
JSP使用上传文件,并生产高清缩略图示例
生成tif文件的拇指图,可指定拇指图的宽和高。tif文件大小不限,运行速度快。
Thumbnailator是Java的缩略图生成库。 为什么选择Thumbnailator? 用Java制作高质量的缩略图可能是一项相当困难的任务。 学习如何使用图像I / O API,Java 2D API,图像处理,图像缩放技术,但不要担心! ...
资源声明:部分资源来自于互联网 代码利用GDAL转TIF文件为png、bmp等格式图片并根据屏幕分辨率对图片进行压缩。解决了因tif文件过大造成内存溢出等问题,欢迎相互学习
java图片压缩文件thumbnailator-0.4.8.jar.zip Thumbnailator是一个用来对图像进行处理以及缩略图的 Java类库,通过很简单的代码即可生成图片缩略图,也可直接对一整个目录的图片生成缩略图。有了它我们就不用在费...
将PRO/E等3D建模工具生成的STL格式的模型文件生成缩略图的工具。 用法 java -jar stl2png.jar -s cube.stl -t cube.png test_stl/stl2png.jar是我编译好的测试包,可以直接使用。 如果成功,则在最后量的输出中可以...
7.ImageThumbnail.java 生成图片缩略图 8.JsonObjs.java json简单操作 9.HttpProxy.java 代理设置 10.CaptureScreen.java 截取桌面 11.XmlReaer.java 读写xml文件 12.ArrayConvers.java 数组与map/list的转换 13....
Thumbnailator是一个为Java界面更流畅的缩略图生成库,从API提供现有的图像文件和图像对象的缩略图中简化了缩略过程,两三行代码就能够从现有图片生成缩略图,使用起来非常方便,需要的朋友可以了解下
java代码保存宽高不变压缩图片(失真不大),按照文件大小,进行压缩质量控制