Java implementation of picture Zoom compression cropping tool! Looking for a long time, the market can no longer find a better than its scaling effect of the code

Source: Internet
Author: User

Original: Java implementation of the picture Zoom compression cropping tool! Looking for a long time, the market can no longer find a better than its scaling effect of the code

Source code: Http://www.zuidaima.com/share/1550463380458496.htm

Pure Java implementation of Picture Zoom compression cropping tool! Do not rely on any third-party jar packages

1. For a long time, the market can no longer find a better than its scaling effect of the code (no third-party components to use the premise)

2. Support Scaling 3. Supports clipping (for example, when a user uploads an avatar and cuts it into a small square image)

/* Copyright 2012-2013 the Haohui Network Corporation */package com.haohui.b2b.util;import java.awt.Color;  Import Java.awt.Graphics2D;  Import Java.awt.Image;  Import Java.awt.rectangle;import java.awt.image.BufferedImage;  Import Java.io.File;  Import Java.io.FileInputStream;  Import Java.io.FileOutputStream;  Import java.io.IOException;  Import Java.net.url;import java.util.Date; Import Java.util.iterator;import Javax.imageio.imageio;import Javax.imageio.imagereadparam;import Javax.imageio.imagereader;import Javax.imageio.stream.imageinputstream;import  Com.sun.image.codec.jpeg.ImageFormatException;  Import Com.sun.image.codec.jpeg.JPEGCodec;  Import Com.sun.image.codec.jpeg.JPEGEncodeParam;    Import Com.sun.image.codec.jpeg.JPEGImageEncoder; /** * Image Compression Tool class provides methods to set the size of the resulting thumbnail image, the scale of the compression size, the quality of the picture, etc. * <pre> * Call Example: * Resiz (srcimg, Tardir + "car_1_maxlength_11-22 0px-hui.jpg ", 0.7F); * </pre> * * @project haohui-b2b * @author Cevencheng www.zuidaima.com * @create2012-3-22 pm 8:29:01 */public class Imageutil {/** * * picture file Read * * @param srcimgpath * @return  */private static BufferedImage Inputimage (String srcimgpath) throws RuntimeException {BufferedImage        Srcimage = null;        FileInputStream in = null;              try {//Construct BufferedImage object File File = new file (Srcimgpath);              in = new FileInputStream (file);              Byte[] B = new Byte[5];              In.read (b);          Srcimage = javax.imageio.ImageIO.read (file);          } catch (IOException e) {e.printstacktrace (); throw new RuntimeException ("Error reading picture File!        ", e); } finally {if (in = null) {try {in.close ();} catch (IOException e) {throw new RuntimeException ("Error reading picture File!        ", E);}}}      return srcimage;  /** * * Compress the picture according to the specified picture size, source image quality (default quality is 1) * * @param srcimgpath *: Source picture Path * @param Outimgpath *: Compression diagram of the outputThe path of the slice * @param new_w *: Compressed picture width * @param new_h *: Compressed picture High */Public STA tic void Resize (string srcimgpath, string outimgpath, int new_w, int new_h) {Resize (Srcimgpath, out      Imgpath, New_w, New_h, 1F); }/** * Compress the picture according to the specified size ratio, source picture quality (default mass is 1) * * @param srcimgpath *: Source picture path * @param o            Utimgpath *: The path of the exported compressed picture * @param ratio *: Compressed picture size ratio * @param per *          : percent */public static void resize (string srcimgpath, string outimgpath, float ratio) {      Resize (Srcimgpath, Outimgpath, ratio, 1F); }/** * Compress the picture by a specified length or width (the default mass is 1) * * @param srcimgpath *: Source picture path * @param o            Utimgpath *: The path of the exported compressed picture * @param maxLength *: Long or wide maximum * @param per * : Picture quality */public static void resize (String srcimgPath, String outimgpath, int maxLength) {Resize (Srcimgpath, Outimgpath, MaxLength, 1F); * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * @param/** * *: Source image Path * @param Outimgpa TH *: The path of the compressed picture of the output * @param new_w *: Compressed picture width * @param new_h *: After compression Picture High * @param per *: Percent * @author Cevencheng */public static void resize (String srcim Gpath, String outimgpath, int new_w, int new_h, float per) {//get picture bufferedimage src = in          Putimage (Srcimgpath);          int old_w = Src.getwidth ();          Get the source map width int old_h = Src.getheight (); Get the source graph length//generate blank canvas based on the original size bufferedimage tempimg = new BufferedImage (Old_w, Old_h, Buffe          REDIMAGE.TYPE_INT_RGB);          Create a thumbnail of the original image on the new canvas graphics2d g = tempimg.creategraphics ();          G.setcolor (Color.White); G.fillRect (0, 0, Old_w, old_h);          G.drawimage (SRC, 0, 0, Old_w, old_h, color.white, NULL);          G.dispose ();          BufferedImage newimg = new BufferedImage (New_w, New_h, Bufferedimage.type_int_rgb);                  Newimg.getgraphics (). DrawImage (Tempimg.getscaledinstance (New_w, New_h, Image.scale_smooth), 0,          0, NULL);      Call method Output picture file Outimage (Outimgpath, newimg, per); }/** * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * @param srcimgpath *: TH *: The path of the compressed picture of the output * @param ratio *: Compressed picture size ratio * @param per *: Hundred points  than * @author Cevencheng */public static void resize (string srcimgpath, string outimgpath, float          Ratio, float per) {//get picture bufferedimage src = inputimage (srcimgpath);          int old_w = Src.getwidth ();      Get the source map width int old_h = Src.getheight ();    Get the source graph length int new_w = 0;          The width int new_h = 0 of the new figure;          The long bufferedimage tempimg of the new figure = new BufferedImage (Old_w, Old_h, Bufferedimage.type_int_rgb);          Graphics2D g = tempimg.creategraphics ();          G.setcolor (Color.White);          Draw a new picture from the original image g.fillrect (0, 0, Old_w, old_h);          G.drawimage (SRC, 0, 0, Old_w, old_h, color.white, NULL);          G.dispose ();          The size of the new figure is new_w = (int) math.round (Old_w * ratio) according to the picture size compression ratio;          New_h = (int) math.round (Old_h * ratio);          BufferedImage newimg = new BufferedImage (New_w, New_h, Bufferedimage.type_int_rgb);                  Newimg.getgraphics (). DrawImage (Tempimg.getscaledinstance (New_w, New_h, Image.scale_smooth), 0,          0, NULL);      Call method Output picture file Outimage (Outimgpath, newimg, per);            }/** * <b> * Specify a maximum value of long or wide to compress the picture * Recommended Use this method * </b> * @param srcimgpath * :SOURCE Picture Path * @param outimgpath *: The path of the exported compressed picture * @param maxLength *: Long or wide maximum value * @p  Aram per *: Picture quality * @author Cevencheng */public static void resize (string srcimgpath, String Outimgpath, int maxLength, float per) {//get picture bufferedimage src = inputimage (srcimgpath)          ;          int old_w = Src.getwidth ();          Get the source map width int old_h = Src.getheight ();          Get the source graph length int new_w = 0;          The width int new_h = 0 of the new figure;          The long bufferedimage tempimg of the new figure = new BufferedImage (Old_w, Old_h, Bufferedimage.type_int_rgb);          Graphics2D g = tempimg.creategraphics ();          G.setcolor (Color.White);          Draw a new picture from the original image g.fillrect (0, 0, Old_w, old_h);          G.drawimage (SRC, 0, 0, Old_w, old_h, color.white, NULL);          G.dispose ();     The size of the new image according to the image size compression ratio if (Old_w > Old_h) {//Picture to scale         New_w = MaxLength;          New_h = (int) math.round (Old_h * ((float) maxlength/old_w));              } else {new_w = (int) math.round (Old_w * ((float) maxlength/old_h));          New_h = MaxLength;          } bufferedimage newimg = new BufferedImage (New_w, New_h, Bufferedimage.type_int_rgb);                  Newimg.getgraphics (). DrawImage (Tempimg.getscaledinstance (New_w, New_h, Image.scale_smooth), 0,          0, NULL);      Call method Output picture file Outimage (Outimgpath, newimg, per); /** * Compress the picture to a specified width, height, etc. scale * * @param srcimgpath * @param outimgpath * @param width * @       Param per */public static void Resizefixedwidth (String srcimgpath, string outimgpath, int width, float per) {      Get picture bufferedimage src = inputimage (srcimgpath);      int old_w = Src.getwidth ();      Get the source map width int old_h = Src.getheight ();      Get the source graph length int new_w = 0; //the width int new_h = 0 of the new figure;      The long bufferedimage tempimg of the new figure = new BufferedImage (Old_w, Old_h, Bufferedimage.type_int_rgb);      Graphics2D g = tempimg.creategraphics ();      G.setcolor (Color.White);      Draw a new picture from the original image g.fillrect (0, 0, Old_w, old_h);      G.drawimage (SRC, 0, 0, Old_w, old_h, color.white, NULL);      G.dispose ();      According to the picture size compression ratio to get the new figure size if (Old_w > Old_h) {//picture to scale new_w = width;      New_h = (int) math.round (Old_h * ((float) width/old_w));      } else {new_w = (int) math.round (Old_w * ((float) width/old_h));      New_h = width;      } bufferedimage newimg = new BufferedImage (New_w, New_h, Bufferedimage.type_int_rgb);      Newimg.getgraphics (). DrawImage (Tempimg.getscaledinstance (New_w, New_h, Image.scale_smooth), 0, 0, NULL);      Call method Output picture file Outimage (Outimgpath, newimg, per); }/** * * Output the picture file to the specified path, and can set the compression quality * * @param outimgpath * @param newimg * @paramper * @author Cevencheng */private static void Outimage (String outimgpath, BufferedImage newimg, float per)          {//Determines if the output folder path exists and does not exist to create the file File = new file (Outimgpath);          if (!file.getparentfile (). exists ()) {File.getparentfile (). Mkdirs ();        }//output to file stream FileOutputStream fos = null;              try {fos = new FileOutputStream (Outimgpath);              JPEGImageEncoder encoder = jpegcodec.createjpegencoder (FOS);              JPEGEncodeParam Jep = Jpegcodec.getdefaultjpegencodeparam (newimg);              Compression quality jep.setquality (per, true);              Encoder.encode (newimg, Jep);          Fos.close ();        } catch (Exception e) {throw new RuntimeException (e);        } finally {if (FOS! = null) {try {fos.close ();} catch (IOException e) {throw new RuntimeException (e);}}   }}/** * Picture Clipping tool Method * * @param srcfile source picture * @param outfile after clipping  * @param x cut vertex x coordinate * @param y-cut vertex y-coordinate * @param width clipping area-height @param height clipping area * * @throws  IOException * @author Cevencheng */public static void cut (file srcfile, file outfile, int x, int y, int width, int Height) throws IOException {FileInputStream is = Null;imageinputstream IIS = null;try {//Read picture file is = new FileInputStream ( Srcfile); */* returns Iterator that contain all currently registered ImageReader, which imagereader claim to decode the specified format. * Parameters: FormatName-contains informal format names. (e.g. "JPEG" or "TIFF"). */iterator<imagereader> it = imageio.getimagereadersbyformatname ("jpg"); ImageReader reader = It.next ();// Get Picture Stream IIS = Imageio.createimageinputstream (IS);/* <p>iis: Read source. True: Search forward only </p> mark it as ' search forward only '. * This setting means that images included in the input source will only be read sequentially and may allow reader to avoid caching of those input parts that contain data associated with previously read images. */reader.setinput (IIS, True);/* * <p> describes how the stream decodes the class <p>. Used to specify how to swap an image or a set of images from the context of the Java Image I/O * Framework at input. The plug-in for a particular image format returns an instance of Imagereadparam from the * Getdefaultreadparam method implemented by its imagereader. */imagereadparam param =Reader.getdefaultreadparam ();/* * Picture clipping area. Rectangle specifies an area in the coordinate space that can be defined by the coordinates (x, y), width, and height of the upper-left vertex of the Rectangle object *. */rectangle rect = new Rectangle (x, y, width, height);//provides a bufferedimage that is used as the target for decoding pixel data. Param.setsourceregion (rect); */* Use the provided Imagereadparam to read the object specified by the index ImageIndex and return it as a full * bufferedimage. */bufferedimage bi = reader.read (0, param);//Save new picture Imageio.write (bi, "JPG", outfile);} Finally {if (is! = null) {Is.close ();}    if (IIS! = null) {Iis.close ();}}          public static void Main (string args[]) throws Exception {string srcimg = "C:/zuidaima/car_2.jpg";          String Tardir = "c:/zuidaima/newimg/";        URL url = ImageUtil.class.getResource ("src-2012.jpg");        File Srcfile = new file (Url.touri ());        System.out.println (URL);        System.out.println (srcfile.exists () + ", dir=" + srcfile.getparent ());        Tardir = Srcfile.getparent ();        Srcimg = Srcfile.getpath ();        System.out.println ("srcimg=" + srcimg); Long StartTime = New Date (). GetTime ();  Resize (srcimg, Tardir + "car_1_maxlength_1-200px.jpg", 200);          Tosmallerpic (srcimg, Tardir + "car_1_maxlength_2.jpg", 0.5F);          Resize (srcimg, Tardir + "car_1_maxlength_3.jpg", 400, 500);          Resize (srcimg, Tardir + "car_1_maxlength_4-400x400.jpg", 220, 220);  Resize (srcimg, Tardir + "car_1_maxlength_11-220px-yinhui.jpg", 0.7F);          Tosmallerpic (srcimg, Tardir + "car_1_maxlength_22.jpg", 0.5F, 0.8F);          Resize (srcimg, Tardir + "car_1_maxlength_33.jpg", 0.8F);      System.out.println (New Date (). GetTime ()-startTime);   }  }

Java implementation of picture Zoom compression cropping tool! Looking for a long time, the market can no longer find a better than its scaling effect of the code

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.