In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article will explain in detail how to use Java to achieve picture cutting function, the editor thinks it is very practical, so share it for you to do a reference, I hope you can get something after reading this article.
The details are as follows
Tool class package com.xudaolong.Utils;import javax.imageio.IIOImage;import javax.imageio.ImageIO;import javax.imageio.ImageReader;import javax.imageio.ImageWriter;import javax.imageio.stream.ImageInputStream;import javax.imageio.stream.ImageOutputStream;import java.awt.*;import java.awt.image.BufferedImage;import java.io.File;import java.io.IOException;import java.util.Arrays;import java.util.Iterator;/** * Image cropping and compression tool class *
* it mainly provides a solution to the phenomenon that only one frame of dynamic effect appears after the dynamic GIF format image is cropped *
* provide a solution that relies on three-party package (parsing one by one according to the data characteristics of GIF format Perform encoding and decoding operations) * provide solutions based on JDK Image BMP O (JDK exploration failed) * / public class ImageCutterUtil {public enum IMAGE_FORMAT {BMP ("bmp"), JPG ("jpg"), WBMP ("wbmp"), JPEG ("jpeg"), PNG ("png"), GIF ("gif") Private String value; IMAGE_FORMAT (String value) {this.value = value;} public String getValue () {return value;} public void setValue (String value) {this.value = value }} / * get picture format * * @ param file picture file * @ return picture format * / public static String getImageFormatName (File file) throws IOException {String formatName = null; ImageInputStream iis = ImageIO.createImageInputStream (file); Iterator imageReader = ImageIO.getImageReaders (iis) If (imageReader.hasNext ()) {ImageReader reader = imageReader.next (); formatName = reader.getFormatName ();} return formatName } / * based on JDK solution * * / / * read pictures * * @ param file picture file * @ return picture data * @ Throws IOException * / public static BufferedImage [] readerImage (File file) throws IOException {BufferedImage sourceImage = ImageIO.read (file) BufferedImage [] images = null; ImageInputStream iis = ImageIO.createImageInputStream (file); Iterator imageReaders = ImageIO.getImageReaders (iis); if (imageReaders.hasNext ()) {ImageReader reader = imageReaders.next (); reader.setInput (iis); int imageNumber = reader.getNumImages (true); images = new BufferedImage [imageNumber]; for (int I = 0; I)
< imageNumber; i++) { BufferedImage image = reader.read(i); if (sourceImage.getWidth() >Image.getWidth () | | sourceImage.getHeight () > image.getHeight () {image = zoom (image, sourceImage.getWidth (), sourceImage.getHeight ());} images [I] = image;} reader.dispose (); iis.close ();} return images } / * process pictures as required * * @ param images picture array * @ param x horizontal start position * @ param y vertical start position * @ param width width * @ param height width * @ return processed picture array * @ throws Exception * / Public static BufferedImage [] processImage (BufferedImage [] images Int x, int y, int width, int height) throws Exception {if (null = = images) {return images } BufferedImage [] oldImages = images; images = new BufferedImage [images.length]; for (int I = 0; I
< oldImages.length; i++) { BufferedImage image = oldImages[i]; images[i] = image.getSubimage(x, y, width, height); } return images; } /** * 写入处理后的图片到file * * 图片后缀根据图片格式生成 * * @param images 处理后的图片数据 * @param formatName 图片格式 * @param file 写入文件对象 * @throws Exception */ public static void writerImage(BufferedImage[] images, String formatName, File file) throws Exception { Iterator imageWriters = ImageIO.getImageWritersByFormatName(formatName); if (imageWriters.hasNext()) { ImageWriter writer = imageWriters.next(); String fileName = file.getName(); int index = fileName.lastIndexOf("."); if (index >0) {fileName = fileName.substring (0, index + 1) + formatName;} String pathPrefix = getFilePrefixPath (file.getPath ()); File outFile = new File (pathPrefix + fileName); ImageOutputStream ios = ImageIO.createImageOutputStream (outFile); writer.setOutput (ios); if (writer.canWriteSequence ()) {writer.prepareWriteSequence (null) For (int I = 0; I
< images.length; i++) { BufferedImage childImage = images[i]; IIOImage image = new IIOImage(childImage, null, null); writer.writeToSequence(image, null); } writer.endWriteSequence(); } else { for (int i = 0; i < images.length; i++) { writer.write(images[i]); } } writer.dispose(); ios.close(); } } /** * 剪切格式图片 * * 基于JDK Image I/O解决方案 * * @param sourceFile 待剪切图片文件对象 * @param destFile 裁剪后保存文件对象 * @param x 剪切横向起始位置 * @param y 剪切纵向起始位置 * @param width 剪切宽度 * @param height 剪切宽度 * @throws Exception */ public static void cutImage(File sourceFile, File destFile, int x, int y, int width, int height) throws Exception { // 读取图片信息 BufferedImage[] images = readerImage(sourceFile); // 处理图片 images = processImage(images, x, y, width, height); // 获取文件后缀 String formatName = getImageFormatName(sourceFile); destFile = new File(getPathWithoutSuffix(destFile.getPath()) + formatName); // 写入处理后的图片到文件 writerImage(images, formatName, destFile); } /** * 获取系统支持的图片格式 */ public static void getOSSupportsStandardImageFormat() { String[] readerFormatName = ImageIO.getReaderFormatNames(); String[] readerSuffixName = ImageIO.getReaderFileSuffixes(); String[] readerMIMEType = ImageIO.getReaderMIMETypes(); System.out.println("========================= OS supports reader ========================"); System.out.println("OS supports reader format name : " + Arrays.asList(readerFormatName)); System.out.println("OS supports reader suffix name : " + Arrays.asList(readerSuffixName)); System.out.println("OS supports reader MIME type : " + Arrays.asList(readerMIMEType)); String[] writerFormatName = ImageIO.getWriterFormatNames(); String[] writerSuffixName = ImageIO.getWriterFileSuffixes(); String[] writerMIMEType = ImageIO.getWriterMIMETypes(); System.out.println("========================= OS supports writer ========================"); System.out.println("OS supports writer format name : " + Arrays.asList(writerFormatName)); System.out.println("OS supports writer suffix name : " + Arrays.asList(writerSuffixName)); System.out.println("OS supports writer MIME type : " + Arrays.asList(writerMIMEType)); } /** * 压缩图片 * * @param sourceImage 待压缩图片 * @param width 压缩图片高度 * @param height 压缩图片宽度 */ private static BufferedImage zoom(BufferedImage sourceImage, int width, int height) { BufferedImage zoomImage = new BufferedImage(width, height, sourceImage.getType()); Image image = sourceImage.getScaledInstance(width, height, Image.SCALE_SMOOTH); Graphics gc = zoomImage.getGraphics(); gc.setColor(Color.WHITE); gc.drawImage(image, 0, 0, null); return zoomImage; } /** * 获取某个文件的前缀路径 * * 不包含文件名的路径 * * @param file 当前文件对象 * @return * @throws IOException */ public static String getFilePrefixPath(File file) throws IOException { String path = null; if (!file.exists()) { throw new IOException("not found the file !"); } String fileName = file.getName(); path = file.getPath().replace(fileName, ""); return path; } /** * 获取某个文件的前缀路径 * * 不包含文件名的路径 * * @param path 当前文件路径 * @return 不包含文件名的路径 * @throws Exception */ public static String getFilePrefixPath(String path) throws Exception { if (null == path || path.isEmpty()) throw new Exception("文件路径为空!"); int index = path.lastIndexOf(File.separator); if (index >0) {path = path.substring (0, index + 1);} return path;} / * * get the file path without suffix * * @ param src * @ return * / public static String getPathWithoutSuffix (String src) {String path = src; int index = path.lastIndexOf (".") If (index > 0) {path = path.substring (0, index + 1);} return path;} / * get the file name * * @ param filePath file path * @ return file name * @ throws IOException * / public static String getFileName (String filePath) throws IOException {File file = new File (filePath) If (! file.exists ()) {throw new IOException ("not found the file!");} return file.getName ();} / * @ param args * @ throws Exception * / public static void main (String [] args) throws Exception {/ / get the supported image format / / ImageCutterUtil.getOSSupportsStandardImageFormat () Try {/ / starting coordinates, cut size int x = 14; int y = 24; int width = 62; int height = 62; / / reference image size int clientWidth = 88; int clientHeight = 88 File file = new File ("/ Users/mac/IdeaProjects/QRdemo/resources/src/com/xudaolong/QR/TestQR/QR.jpg"); BufferedImage image = ImageIO.read (file); double destWidth = image.getWidth (); double destHeight = image.getHeight (); if (destWidth < width | | destHeight < height) throw new Exception ("the size of the source image is smaller than the size of the captured image!") Double widthRatio = destWidth / clientWidth; double heightRatio = destHeight / clientHeight; x = Double.valueOf (x * widthRatio). IntValue (); y = Double.valueOf (y * heightRatio). IntValue (); width = Double.valueOf (width * widthRatio). IntValue (); height = Double.valueOf (height * heightRatio). IntValue () System.out.println ("crop size x:" + x + ", y:" + y + ", width:" + width + ", height:" + height); String formatName = getImageFormatName (file); String pathSuffix = "." + formatName; String pathPrefix = getFilePrefixPath (file); String targetPath = pathPrefix + System.currentTimeMillis () + pathSuffix; File destFile = new File (targetPath) ImageCutterUtil.cutImage (file, destFile, x, y, width, height);} catch (IOException e) {e.printStackTrace ();} unilaterally test public void cutQR (String sourcePath) {try {File file = new File (sourcePath); BufferedImage image = ImageIO.read (file) / / initial coordinates, cut size int x = 14; int y = 25; int width = 62; int height = 62; / / reference image size int clientWidth = 88; int clientHeight = 88; double destWidth = image.getWidth (); double destHeight = image.getHeight () If (destWidth < width | | destHeight < height) throw new Exception ("the size of the source image is smaller than the size of the captured image!"); double widthRatio = destWidth / clientWidth; double heightRatio = destHeight / clientHeight; / / modify the unit x = Double.valueOf (x * widthRatio). IntValue (); y = Double.valueOf (y * heightRatio). IntValue () Width = Double.valueOf (width * widthRatio). IntValue (); height = Double.valueOf (height * heightRatio). IntValue (); System.out.println ("crop size x:" + x + ", y:" + y + ", width:" + width + ", height:" + height); / / get the specified name / / String formatName = getImageFormatName (file) / / String pathSuffix = "." + formatName;// String pathPrefix = getFilePrefixPath (file); / / String targetPath = pathPrefix + System.currentTimeMillis () + pathSuffix; / / the last step is cropped to the specified name File destFile = new File (sourcePath); ImageCutterUtil.cutImage (file, destFile, x, y, width, height) } catch (Exception e) {e.printStackTrace ();}} this is the end of the article on "how to use Java to achieve image cutting". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.