1. Thumbnail
When browsing albums, you may need to generate corresponding thumbnails.
Directly upload the code:
public class ImageUtil { private Logger log = LoggerFactory.getLogger(getClass()); private static String DEFAULT_PREVFIX = "thumb_"; private static Boolean DEFAULT_FORCE = false;//It is recommended that this value be false /** * <p>Title: thumbnailImage</p> * <p>Description: Generate thumbnails based on the image path</p> * @param imagePath Original image path* @param w Thumbnail width* @param h Thumbnail height* @param prevfix Generate the prefix of thumbnails* @param force Whether to force thumbnails to be generated according to width and height (if false, the best scale thumbnail is generated) */ public void thumbnailImage(String imagePath, int w, int h, String prevfix, boolean force){ File imgFile = new File(imagePath); if(imgFile.exists()){ try { // ImageIO Supported image types: [BMP, bmp, jpg, JPG, wbmp, jpeg, png, PNG, JPEG, WBMP, GIF, gif] String types = Arrays.toString(ImageIO.getReaderFormatNames()); String suffix = null; // Get the image suffix if(imgFile.getName().indexOf(".") > -1) { suffix = imgFile.getName().substring(imgFile.getName().lastIndexOf(".") + 1); }// Type and image suffix are all lowercase, and then determine whether the suffix is legal if(suffix == null || types.toLowerCase().indexOf(suffix.toLowerCase()) < 0){ log.error("Sorry, the image suffix is illegal. the standard image suffix is {}." + types); return ; } log.debug("target image's size, width:{}, height:{}.",w,h); Image img = ImageIO.read(imgFile); if(!force){ // Find the most suitable thumbnail scale based on the original image and the required thumbnail scale int width = img.getWidth(null); int height = img.getHeight(null); if((width*1.0)/w < (height*1.0)/h){ if(width > w){ h = Integer.parseInt(new java.text.DecimalFormat("0").format(height * w/(width*1.0))); log.debug("change image's height, width:{}, height:{}.",w,h); } } else { if(height > h){ w = Integer.parseInt(new java.text.DecimalFormat("0").format(width * h/(height*1.0))); log.debug("change image's width, width:{}, height:{}.",w,h); } } } BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB); Graphics g = bi.getGraphics(); g.drawImage(img, 0, 0, w, h, Color.LIGHT_GRAY, null); g.dispose(); String p = imgFile.getPath(); // Save the image in the original directory and prefix ImageIO.write(bi, suffix, new File(p.substring(0,p.lastIndexOf(File.separator)) + File.separator + prevfix +imgFile.getName())); log.debug("Thumbnail generated successfully in the original path"); } catch (IOException e) { log.error("generate thumbnail image failed.",e); } }else{ log.warn("the image is not exist."); } } public static void main(String[] args) { new ImageUtil().thumbnailImage("C:/Users/cm/Desktop/My page/images/girlNoImg.jpg", 100, 150,DEFAULT_PREVFIX,DEFAULT_FORCE); }}Run the main method directly and fill in the corresponding parameters.
2. Cooperate with js to generate cropped pictures
When we modify our personal Weibo and QQ information, we can upload our personal avatars, and then cut our personal avatars and upload them. The size and style of cropped images are implemented through JavaScript, but it does not generate a new image. However, js cropped images provide the x and y coordinates and width and height of the image. Through these four parameters, we can generate new cropped images based on the original image.
step:
1. First, I used js to realize the image cut and browsing function through the page. I referred to the information provided by MOOC and changed it slightly. In addition, we can also use plug-ins, such as Jcrop, which is a very good picture cropping plug-in.
Download address: http://download.csdn.net/detail/u012385190/9733480
The final rendering is as above. You can drag and drag on the left, and the preview picture on the right.
2. Java generates and saves cut pictures
public class ImageUtil2 { private Logger log = LoggerFactory.getLogger(getClass()); private static String DEFAULT_CUT_PREVFIX = "cut_"; /** * Description: Intercept local images based on the original image and crop size* @param srcImg Source image* @param output Image output stream* @param rect The coordinates and size of the part need to be intercepted*/ public void cutImage(File srcImg, OutputStream output,java.awt.Rectangle rect) { if (srcImg.exists()) { java.io.FileInputStream fis = null; ImageInputStream iis = null; try { fis = new FileInputStream(srcImg); // ImageIO Supported Image Types: [BMP, bmp, jpg, JPG, wbmp, jpeg, png, PNG, // JPEG, WBMP, GIF, gif] String types = Arrays.toString(ImageIO.getReaderFormatNames()) .replace("]", ","); String suffix = null; // Get the image suffix if (srcImg.getName().indexOf(".") > -1) { suffix = srcImg.getName().substring(srcImg.getName().lastIndexOf(".") + 1); }// The type and image suffix are all lowercase, and then determine whether the suffix is legal if (suffix == null || types.toLowerCase().indexOf(suffix.toLowerCase() + ",") < 0) { log.error("Sorry, the image suffix is illegal. the standard image suffix is {}."+ types); return; } // Convert FileInputStream to ImageInputStream iis = ImageIO.createImageInputStream(fis); // Get the ImageReader of this type according to the image type ImageReader reader = ImageIO.getImageReadersBySuffix(suffix).next(); reader.setInput(iis, true); ImageReadParam param = reader.getDefaultReadParam(); param.setSourceRegion(rect); BufferedImage bi = reader.read(0, param); ImageIO.write(bi, suffix, output); log.info("The image is generated successfully, please go to the directory to view"); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (fis != null) fis.close(); if (iis != null) iis.close(); } catch (IOException e) { e.printStackTrace(); } } } else { log.warn("the src image is not exist."); } } // Generate the target file path public void cutImage(File srcImg, String destImgPath,java.awt.Rectangle rect) { File destImg = new File(destImgPath); if (destImg.exists()) { String p = destImg.getPath(); try { if (!destImg.isDirectory()) p = destImg.getParent(); if (!p.endsWith(File.separator)) p = p + File.separator; cutImage(srcImg,new java.io.FileOutputStream(p + DEFAULT_CUT_PREVFIX+ "_"+ srcImg.getName()), rect); } catch (FileNotFoundException e) { log.warn("the dest image is not exist."); } } else log.warn("the dest image folder is not exist."); } public void cutImage(String srcImg, String destImg, int x, int y, int width, int height) { cutImage(new File(srcImg), destImg, new java.awt.Rectangle(x, y, width, height)); } public static void main(String[] args) { new ImageUtil2().cutImage("C:/Users/cm/Desktop/My page/images/boyNoImg.jpg", "C:/Users/cm/Desktop/My page/images/imgs",0, 0, 61, 166); //new ImageUtil2().cutImage("C:/Users/cm/Desktop/Jcrop-master/demos/demo_files/sago.jpg", "C:/Users/cm/Desktop/My Page/images/imgs",124, 110, 196, 176); }}This method can be run directly in main. The four parameters passed in are image path, left value, top value, length and width.
Let’s analyze how to obtain these four parameters:
1. Taking my js cut as an example, I get the following through F12:
The red part in the picture is the div of the picture cut. We can observe which parameters have been changed by dragging the size and width of the clipping area, etc., and then determine which parameter values correspond to the specific corresponding parameter values. As in the picture, my x/y/width/height is 40,28,224,228 respectively.
Note: In js, I define the length and width of the div and the image as 300*300. In order to cooperate with the test, the image I downloaded is also 300*300. If the image you tested is not 300*300, then the effect you tested directly in java above will be different from what you see in front end, because I define the width and height of your front end image as 300*300, while your actual image (i.e., the image in java) is not.
So what if this problem is handled?
Get the length and width of the original image in your java code, and then determine whether the length and width of the original image are 300*300. If not, generate a 300*300 thumbnail of the image, and then use the 300*300 thumbnail as the cropped image prototype. (My code does not process it, I will process it myself if I need it, and delete the thumbnails after using up the picture)
2. Jcrop gets parameters
As shown in the figure, Jcrop directly provides parameters and can be used directly. But one disadvantage is that the image size area of the front-end page is not fixed. If you have a large pixel image, it will be very ugly. For example, if I have an image soga_bak.jpg in the corresponding file, it will be bad if I replace it with this image.
So in summary, it is recommended to use the first js, and then determine whether the length and width of the original image are 300, and generate a 300*300 thumbnail, then use the thumbnail as a crop prototype, and then delete the thumbnail after using it.
The above is the example method of Java image cropping and generating thumbnails introduced to you by the editor. It is an invalid issue for Get requests. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support to Wulin.com website!