Java implementation to generate picture thumbnails, reduce high-definition pictures

Source: Internet
Author: User

Import Com.sun.image.codec.jpeg.jpegimageencoder;import Com.sun.image.codec.jpeg.jpegcodec;import Com.sun.image.codec.jpeg.jpegencodeparam;import Javax.imageio.imageio;import Java.awt.image.BufferedImage;import Java.util.hashmap;import java.util.list;import java.util.arraylist;import Java.io.file;import java.io.IOException;     Import Java.io.fileoutputstream;import Java.util.map;public class Resizeimage {/** * @param im RAW image * @param resizetimes need to be reduced by multiples of twice times the original 1/2, the larger the value, the smaller the returned image * @return return the processed image */public Bufferedi        Mage resizeimage (BufferedImage im, float resizetimes) {/* the width and height of the original image */int width = im.getwidth ();        int height = im.getheight ();        /* Width and height of adjusted picture */int towidth = (int) (Float.parsefloat (string.valueof (width))/resizetimes);        int toheight = (int) (Float.parsefloat (string.valueof (height))/resizetimes); /* New Build result picture */bufferedimage result = new BufferedImage (Towidth, Toheight, BufFEREDIMAGE.TYPE_INT_RGB);        Result.getgraphics (). DrawImage (Im.getscaledinstance (Towidth, Toheight, Java.awt.Image.SCALE_SMOOTH), 0, 0, NULL);    return result;              }/** * @param im RAW image * @param resizetimes multiples, such as 0.5 is reduced by half, 0.98, and so on double type * @return Returns the processed image */public bufferedimage zoomimage (BufferedImage im, float resizetimes) {/* the width and height of the original image */I        NT width = im.getwidth ();        int height = im.getheight ();        /* Width and height of the resized picture */int towidth = (int) (Float.parsefloat (string.valueof (width)) * resizetimes);        int toheight = (int) (Float.parsefloat (string.valueof (height)) * resizetimes);        /* New generated result picture */bufferedimage result = new BufferedImage (Towidth, Toheight, Bufferedimage.type_int_rgb);        Result.getgraphics (). DrawImage (Im.getscaledinstance (Towidth, Toheight, Java.awt.Image.SCALE_SMOOTH), 0, 0, NULL);    return result; }/** * @param path to the folder of the image to be converted is the folder path where the image is stored * @param tyAn array of suffix names for PE pictures * @return */public list<bufferedimage> getimagelist (String path, string[] type) throws IO        exception{map<string,boolean> Map = new hashmap<string, boolean> ();        for (String s:type) {map.put (s,true);        } list<bufferedimage> result = new arraylist<bufferedimage> ();        file[] fileList = new File (path). Listfiles ();            for (File f:filelist) {if (f.length () = = 0) continue;            if (Map.get (GetExtension (f.getname)) = = null) continue;        Result.add (Javax.imageio.ImageIO.read (f));    } return result; /** * Write the picture to disk * @param im * @param path eg:c://home//Picture Write folder address * @param fileName dcm1987.jp G Write the name of the picture * @return */public boolean writetodisk (BufferedImage im, string path, String fileName) {Fi        Le f = new File (path + fileName);    String FileType = getextension (fileName);    if (FileType = = null) return false;            try {imageio.write (IM, fileType, f);            Im.flush ();        return true;        } catch (IOException e) {return false;            }} public boolean writehighquality (BufferedImage im, String filefullpath) {try {* * * output to file stream */            FileOutputStream newimage = new FileOutputStream (Filefullpath+system.currenttimemillis () + ". jpg");            JPEGImageEncoder encoder = Jpegcodec.createjpegencoder (newimage);            JPEGEncodeParam Jep = Jpegcodec.getdefaultjpegencodeparam (IM);            /* Compression Quality */jep.setquality (1f, true);           Encoder.encode (IM, Jep);            /* Near JPEG encoding */newimage.close ();        return true;        } catch (Exception e) {return false; }}/** * return file suffix name * @param fileName * @return * * * public string GetExtension (string fileName) {try {return filename.split ("\\.") [Filename.split ("\ \").        LENGTH-1];        } catch (Exception e) {return null;          }} public static void Main (string[] args) throws exception{String Inputfoler = "C:\\cameraimage";          /* Fill in the folder you want to shrink the full address of the image */String OutputFolder = "c:\\output\\";         /* Fill in the folder where you converted your pictures */float times = 0.5f;   /* This parameter is to be converted to a multiple, if 1 is converted to 1 time times */resizeimage r = new Resizeimage ();        list<bufferedimage> imageList = r.getimagelist (inputfoler,new string[] {"JPG"});  for (BufferedImage i:imagelist) {r.writehighquality (R.zoomimage (i,times), OutputFolder); }    }}

If you cannot import the jar package, use the following solution:

Error:
Access restriction:the type Jpegcodec isn't accessible due to restriction on required library C:\Program files\java\jre6\ Lib\rt.jar

Workaround:
Project--Properties--Libraries,

Remove the JRE System Library first, and then add the library to rejoin.

============================================

processing pictures in eclipse requires the introduction of two packages:
import Com.sun.image.codec.jpeg.JPEGCodec;
import Com.sun.image.codec.jpeg.JPEGImageEncoder;
error:
access restriction:the type JPEGImageEncoder isn't accessible due to restriction on required library C:\JAVA\JRE1.6.0_07\LIB\RT.JAR


solution at this time:
eclipse By default sets these access-restricted APIs to error. Just put windows-preferences-java-complicer-errors/warnings inside the deprecated and restricted API in forbidden references (access Rules) can be compiled by selecting the warning.

Prioritize the first option


Own use cases in the integration of projects:


Package Webservice.util;import Javax.imageio.imageio;import Com.sun.image.codec.jpeg.jpegcodec;import Com.sun.image.codec.jpeg.jpegencodeparam;import Com.sun.image.codec.jpeg.jpegimageencoder;import Java.awt.image.bufferedimage;import Java.util.hashmap;import Java.util.list;import Java.util.ArrayList;import Java.io.file;import Java.io.ioexception;import Java.io.fileoutputstream;import Java.util.Map;public class resizeimage {/** * @param im original image * @param resizetimes need to be reduced by a multiple of twice times the original 1/2, the larger the value, the smaller the returned picture * @return return the processed image */public bufferedimage resizeimage (BufferedImage im, float resizetimes) {/* Original        Width and height of the starting image */int width = im.getwidth ();        int height = im.getheight ();        /* Width and height of adjusted picture */int towidth = (int) (Float.parsefloat (string.valueof (width))/resizetimes);        int toheight = (int) (Float.parsefloat (string.valueof (height))/resizetimes); /* New generated result picture */bufferedimage result = BufferedimagE (Towidth, Toheight, Bufferedimage.type_int_rgb);        Result.getgraphics (). DrawImage (Im.getscaledinstance (Towidth, Toheight, Java.awt.Image.SCALE_SMOOTH), 0, 0, NULL);    return result;              }/** * @param im RAW image * @param resizetimes multiples, such as 0.5 is reduced by half, 0.98, and so on double type * @return        Returns the processed image */public bufferedimage zoomimage (BufferedImage im) {/* the width and height of the original image */* Width and height of the resized picture */*        int towidth=64;        int toheight=64;        /* New generated result picture */bufferedimage result = new BufferedImage (Towidth, Toheight, Bufferedimage.type_int_rgb);        Result.getgraphics (). DrawImage (Im.getscaledinstance (Towidth, Toheight, Java.awt.Image.SCALE_SMOOTH), 0, 0, NULL);    return result; }/** * @param path the folder of the image to be converted is the folder path that holds the image * @param an array of suffix names for the type picture * @return */Public list<b Ufferedimage> getimagelist (String path, string[] type) throws ioexception{map<string,boolean> Map = new H Ashmap<sTring, boolean> ();        for (String s:type) {map.put (s,true);        } list<bufferedimage> result = new arraylist<bufferedimage> ();        file[] fileList = new File (path). Listfiles ();            for (File f:filelist) {if (f.length () = = 0) continue;            if (Map.get (GetExtension (f.getname)) = = null) continue;        Result.add (Javax.imageio.ImageIO.read (f));    } return result;    Public bufferedimage getImage (String path) throws ioexception{return Javax.imageio.ImageIO.read (new File); /** * Write the picture to disk * @param im * @param path eg:c://home//Picture Write folder address * @param fileName DCM1987        . jpg writes the name of the picture * @return */public boolean writetodisk (BufferedImage im, string path, string fileName) {        File F = new file (path + fileName);        String FileType = getextension (fileName);        if (FileType = = null) return false; try {            Imageio.write (IM, fileType, f);            Im.flush ();        return true;        } catch (IOException e) {return false;            }} public boolean writehighquality (BufferedImage im, String filefullpath) {try {* * * output to file stream */            FileOutputStream newimage = new FileOutputStream (Filefullpath);            JPEGImageEncoder encoder = Jpegcodec.createjpegencoder (newimage);            JPEGEncodeParam Jep = Jpegcodec.getdefaultjpegencodeparam (IM);            /* Compression Quality */jep.setquality (1f, true);           Encoder.encode (IM, Jep);            /* Near JPEG encoding */newimage.close ();        return true;        } catch (Exception e) {return false; }}/** * return file suffix name * @param fileName * @return * * * public string GetExtension (string fileName) {try {return filename.split ("\ \.") [Filename.split ("\ \").        LENGTH-1]; } catch (Exception e) {return null;       }}//test public static void main (string[] args) throws exception{/*system.out.println (123);          String Inputfoler = "F:\\testimages\\yuan";          Fill in the folder where you want to shrink the picture. Full address String OutputFolder = "F:\\testimages\\ys";         Here fill in the folder you converted the picture to hold float times = 0.5f;         This parameter is to be converted to a multiple, if 1 is converted to 1 time times resizeimage r = new Resizeimage ();        list<bufferedimage> imageList = r.getimagelist (inputfoler,new string[] {"PNG"});         for (BufferedImage i:imagelist) {r.writehighquality (R.zoomimage (i,times), OutputFolder);  System.out.println ("...");    }*/resizeimage r=new resizeimage ();    String filepath= "e:\\file\\";    String filename= "1.jpg";    BufferedImage im=r.getimage (filepath+filename); R.writehighquality (R.zoomimage (IM), filepath+ "S_" +filename);//To prevent overwriting the original picture, add S_ to distinguish the image after compression}}




Java implementation to generate picture thumbnails, reduce high-definition pictures

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.