Java picture processing-How to generate high definition and occupy small disk thumbnails

Source: Internet
Author: User

Now the Web project, the picture is more and more, the picture size is also getting larger and bigger, casually can reach 1m,2m, even bigger. The user uploads the picture, generally cannot use directly. Generally to generate two or three of corresponding thumbnails, respectively, suitable for different terminals, different scenes. such as PC, mobile phone, tablet and so on different terminal; In the list of slices and picture details, definitely one to use the thumbnail, one to use the HD map.

The first step in general picture optimization is to use thumbnails where appropriate, and try not to use CSS to scale HD original images on the web side. The following is an analysis of how different thumbnails are generated in Java.

Common picture formats are: ". *\\. (? i) (jpg|jpeg|gif|bmp|png) "

There are two kinds of these, PNG and GIF are one, other format is one, because PNG and GIF has the problem of transparency, if the same as JPG, it will result in a black background picture.

1. Specify the height of the scale Picture:

    /*** Scale pictures by a specified height, etc. *@paramImageFile *@paramNewPath *@paramNewwidth width of New chart *@throwsIOException*/PublicStaticvoid Zoomimagescale (File imagefile, String NewPath,int newwidth)ThrowsIOException {if (!Imagefile.canread ())Return; BufferedImage BufferedImage =Imageio.read (ImageFile);if (NULL = =BufferedImage)Returnint originalwidth = Bufferedimage.getwidth (); int originalheight = Bufferedimage.getheight (); double scale = (double) OriginalWidth/(double) Newwidth; // scale int newheight = (int) (originalheight/ scale);  Zoomimageutils (ImageFile, NewPath, BufferedImage,  Newwidth, newheight);}      
    PrivateStaticvoid Zoomimageutils (File imagefile, String NewPath, BufferedImage bufferedimage,int width,IntHeightThrowsioexception{String suffix = stringutils.substringafterlast (Imagefile.getname (), ".");//Dealing with PNG background blackened issuesif (suffix! =Null && (Suffix.trim (). toLowerCase (). EndsWith ("png") | | Suffix.trim (). toLowerCase (). EndsWith ("GIF")) {BufferedImage to=NewBufferedImage (width, height, bufferedimage.type_int_rgb); Graphics2D g2d =To.creategraphics (); to =G2d.getdeviceconfiguration (). Createcompatibleimage (width, height, transparency.translucent); G2d.dispose (); G2d =To.creategraphics (); Image from =Bufferedimage.getscaledinstance (width, height, image.scale_area_averaging); G2d.drawimage (from, 0, 0,Null); G2d.dispose (); Imageio.write (To, suffix,NewFile (NewPath)); }Else{//High-quality compression, in fact, not much to the definition of help//BufferedImage tag = new BufferedImage (width, height, bufferedimage.type_int_rgb);//Tag.getgraphics (). DrawImage (bufferedimage, 0, 0, width, height, null);////FileOutputStream out = new FileOutputStream (NewPath);//Write a picture to NewPath//JPEGImageEncoder encoder = Jpegcodec.createjpegencoder (out);//JPEGEncodeParam Jep = Jpegcodec.getdefaultjpegencodeparam (tag);// Jep.setquality (1f, true); // compression quality, 1 is the highest value // Encoder.encode (tag, Jep); // Out.close ();  BufferedImage newimage = new  BufferedImage (width, height, bufferedimage.gettype ()); Graphics g = Newimage.getgraphics (); G.drawimage (bufferedimage, 0, 0, width, height, Span style= "color: #0000ff;" >null); G.dispose (); Imageio.write (newimage, suffix, new File (NewPath));}}  

The above Zoomimagescale can specify the height of the resulting picture, and then the width of the new picture is calculated from the aspect ratio of the original graph, so you can also specify the width of the resulting picture to generate a new picture at equal proportions. The Zoomimageutils method involves three image processing methods:

1) normal redraw of the image according to the specified height and width :

            New bufferedimage (width, height, bufferedimage.gettype ());            Graphics g = newimage.getgraphics ();            null);            G.dispose ();            new File (NewPath));    

2) Use jpegimageencoder to generate so-called "high-quality" images :

            //High-quality compression, in fact, not much to the definition of help//BufferedImage tag = new BufferedImage (width, height, bufferedimage.type_int_rgb);//Tag.getgraphics (). DrawImage (bufferedimage, 0, 0, width, height, null);////  fileoutputstream out = new FileOutputStream (NewPath); // write the picture to NewPath// JPEGImageEncoder encoder = Jpegcodec.createjpegencoder (out);  JPEGEncodeParam Jep = jpegcodec.getdefaultjpegencodeparam (tag); // jep.setquality (1f, true); // compression quality, 1 is the highest value // Encoder.encode (tag, Jep);  out.close ();                

This method, in fact, is only the image generated by the larger hard disk, but in fact, the image of the clarity, there is no practical effect.

3)PNG and GIF pictures cannot use the image processing method mentioned above, because it will cause the resulting picture background to become black, to be processed separately (Specify transparent processing):

            New bufferedimage (width, height, bufferedimage.type_int_rgb);             Graphics2D g2d = to.creategraphics ();             to = g2d.getdeviceconfiguration (). Createcompatibleimage (Width,height, transparency.translucent);             G2d.dispose ();                         G2d = to.creategraphics (); Image from =nullnew File (NewPath));     

4) linear processing , this method also cannot handle PNG pictures:

    /*** Equal proportions change picture size *@paramNW New Picture Width *@paramOldimage Original Picture *@throwsIOException*/PublicStaticvoid Constrainproportios (int NW, String oldimage)ThrowsIOException {AffineTransform transform =NewAffineTransform (); BufferedImage bis = Imageio.read (NewFile (oldimage));int w =Bis.getwidth ();int h =Bis.getheight ();int nh = (NW * h)/WDouble SX = (Double) NW/ W; double sy = (double) NH/new affinetransformop (Transform, null); BufferedImage bid = new BufferedImage (NW, NH, BUFFEREDIMAGE.TYPE_3BYTE_BGR); Ato.filter (bis, Bid); String NewPath = Stringutils.substringbeforelast (Oldimage, ".") + "_3." +stringutils.substringafterlast (Oldimage, ".") ); Imageio.write (BID, "JPEG", new File (NewPath)); // Imageio.write (BID," JPEG ", Response.getoutputstream ());}     

There are 4 of images in the generation method, in addition to PNG need to deal with other, several other pictures of the processing method, with the actual resulting image of the clarity of comparison, in fact, the difference is not small, basically no obvious difference. The actual test found that if the image to be generated and the original picture, in terms of clarity to achieve with the naked eye can not clearly distinguish their effects, the key is not to use which image generation method, the key is not to let the resulting image width and height is too small ! This is the key, the actual test found that the width and height of the resulting picture should not be less than 500, must not be less than the.

2. Create a picture with the specified height and width:

    /*** Zoom Image by Size * *@paramImageFile *@paramNewPath *@paramTimes *@throwsIOException*/Publicstatic void zoomimage (File imagefile, String NewPath, Span style= "color: #0000ff;" >int width, int height) throws  IOException {if (imagefile! = null &&! imagefile.canread ()) return Imageio.read (ImageFile); if (null == BufferedImage) return; 

Instead of generating a picture according to the original image's Gaucombilai, the image is generated by the specified height and width. In general, it is best not to choose this approach, because the picture will be compressed or stretched, and the picture will become more ugly.

3. Actual effect comparison:

1) Original image: X 220k

2) According to the specified height of the image generated, the specified height of 448, 33.7k

3) General redraw picture with width and height less than 400, 224 x, 12.9k

4) JPEGImageEncoder with width and height less than 400 generate so-called "high-quality" pictures, 224 x, 63.4k

5) above four kinds of pictures in the Web page, follow the same image as specified in CSS following the performance:

img {    height:auto;    max-height:300px;    max-width:224px;    Width:auto;} 

It can be obvious that the sharpness of the first and second pictures is very close, you can't even say the picture is clearer, and the third Zhang and the fourth kind of picture, from the forehead of the hair, it is significantly worse than the first and the second one.

The actual pictures were:

The first one: a picture generated at a specified height equal to 448, 33.7k

Second: Original image:x 220k

Third: General redraw picture with width and height less than 400,224 x 12.9k

Page four: JPEGImageEncoder with width and height less than 400 produce so-called "high-quality" pictures,224 x 63.4k

Conclusion :

The sharpness of the resulting picture depends primarily on the height and width of the resulting picture, rather than on the algorithm that the picture generates;

If you want to achieve the naked eye can not be separated by the effect, the height of the image is not less than 500, must not be less than 400;

-----

The image of the picture reached 63.4K, but the sharpness was significantly worse than the first picture with a size of only 33.7K. The size of the width and height of the image is the determining factor of clarity.

The third picture is only 12.9K, and the sharpness and the image sharpness of the fourth 63.4K are almost the same, because they are the same size, all 224 x 300, although the algorithm for generating pictures is different.

Java picture processing-How to generate high definition and occupy small disk thumbnails

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.