JAVA,gif 그림 크기 조정 및 잘라 내기 기능 구현
17122 단어 자바 도구 클래스자바 이미지 처리그림 편집 및 크기 조정
자바 이미지 처리 도구 클래스:
package com.pinker.util;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Iterator;
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;
/**
*
*
* GIF ,
*
* ( GIF , )
* JDK Image I/O (JDK )
*/
public class ImageUtil2 {
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;
}
}
/**
*
* @param file
* @return
*/
public static String getImageFormatName(File file)throws IOException{
String formatName = null;
ImageInputStream iis = ImageIO.createImageInputStream(file);
Iterator<ImageReader> imageReader = ImageIO.getImageReaders(iis);
if(imageReader.hasNext()){
ImageReader reader = imageReader.next();
formatName = reader.getFormatName();
}
return formatName;
}
/************************* *****************************/
/**
*
*
* @param source
* @param targetPath ( )
* @param x
* @param y
* @param width
* @param height
*
* @returns ( )
* @throws IOException
*/
public static String cutImage(String sourcePath , String targetPath , int x , int y , int width , int height) throws IOException{
File file = new File(sourcePath);
if(!file.exists()) {
throw new IOException("not found the image:" + sourcePath);
}
if(null == targetPath || targetPath.isEmpty()) targetPath = sourcePath;
String formatName = getImageFormatName(file);
if(null == formatName) return targetPath;
formatName = formatName.toLowerCase();
//
String pathPrefix = getPathWithoutSuffix(targetPath);
targetPath = pathPrefix + formatName;
// GIF
if(IMAGE_FORMAT.GIF.getValue() == formatName){
GifDecoder decoder = new GifDecoder();
int status = decoder.read(sourcePath);
if (status != GifDecoder.STATUS_OK) {
throw new IOException("read image " + sourcePath + " error!");
}
AnimatedGifEncoder encoder = new AnimatedGifEncoder();
encoder.start(targetPath);
encoder.setRepeat(decoder.getLoopCount());
for (int i = 0; i < decoder.getFrameCount(); i ++) {
encoder.setDelay(decoder.getDelay(i));
BufferedImage childImage = decoder.getFrame(i);
BufferedImage image = childImage.getSubimage(x, y, width, height);
encoder.addFrame(image);
}
encoder.finish();
}else{
BufferedImage image = ImageIO.read(file);
image = image.getSubimage(x, y, width, height);
ImageIO.write(image, formatName, new File(targetPath));
}
//
BufferedImage image = ImageIO.read(file);
image = image.getSubimage(x, y, width, height);
ImageIO.write(image, formatName, new File(targetPath));
return targetPath;
}
/**
*
* @param sourcePath
* @param targetPath ( )
* @param width
* @param height
*
* @returns ( )
* @throws IOException
*/
public static String zoom(String sourcePath , String targetPath, int width , int height) throws IOException{
File file = new File(sourcePath);
if(!file.exists()) {
throw new IOException("not found the image :" + sourcePath);
}
if(null == targetPath || targetPath.isEmpty()) targetPath = sourcePath;
String formatName = getImageFormatName(file);
if(null == formatName) return targetPath;
formatName = formatName.toLowerCase();
//
String pathPrefix = getPathWithoutSuffix(targetPath);
targetPath = pathPrefix + formatName;
// GIF
if(IMAGE_FORMAT.GIF.getValue() == formatName){
GifDecoder decoder = new GifDecoder();
int status = decoder.read(sourcePath);
if (status != GifDecoder.STATUS_OK) {
throw new IOException("read image " + sourcePath + " error!");
}
AnimatedGifEncoder encoder = new AnimatedGifEncoder();
encoder.start(targetPath);
encoder.setRepeat(decoder.getLoopCount());
for (int i = 0; i < decoder.getFrameCount(); i ++) {
encoder.setDelay(decoder.getDelay(i));
BufferedImage image = zoom(decoder.getFrame(i), width , height);
encoder.addFrame(image);
}
encoder.finish();
}else{
BufferedImage image = ImageIO.read(file);
BufferedImage zoomImage = zoom(image , width , height);
ImageIO.write(zoomImage, formatName, new File(targetPath));
}
BufferedImage image = ImageIO.read(file);
BufferedImage zoomImage = zoom(image , width , height);
ImageIO.write(zoomImage, formatName, new File(targetPath));
return targetPath;
}
/*********************** JDK ********************************/
/**
*
* @param file
* @return
* @throws IOException
*/
public static BufferedImage[] readerImage(File file) throws IOException{
BufferedImage sourceImage = ImageIO.read(file);
BufferedImage[] images = null;
ImageInputStream iis = ImageIO.createImageInputStream(file);
Iterator<ImageReader> 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;
}
/**
*
*
* @param images
* @param x
* @param y
* @param width
* @param height
* @return
* @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<ImageWriter> 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 heigt
*/
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;
}
/**
*
*
* @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;
}
/**
*
* @param filePath
* @return
* @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 {
//
//ImageCutterUtil.getOSSupportsStandardImageFormat();
try {
// ,
int x = 100;
int y = 75;
int width = 100;
int height = 100;
//
int clientWidth = 300;
int clientHeight = 250;
File file = new File("C:\\1.jpg");
BufferedImage image = ImageIO.read(file);
double destWidth = image.getWidth();
double destHeight = image.getHeight();
if(destWidth < width || destHeight < height)
throw new Exception(" !");
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(" 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;
targetPath = ImageUtil2.cutImage(file.getPath(), targetPath, x , y , width, height);
String bigTargetPath = pathPrefix + System.currentTimeMillis() + pathSuffix;
ImageUtil2.zoom(targetPath, bigTargetPath, 100, 100);
String smallTargetPath = pathPrefix + System.currentTimeMillis() + pathSuffix;
ImageUtil2.zoom(targetPath, smallTargetPath, 50, 50);
/************************ JDK Image I/O (JDK ) *************************/
// File destFile = new File(targetPath);
// ImageCutterUtil.cutImage(file, destFile, x, y, width, height);
} catch (IOException e) {
e.printStackTrace();
}
}
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
자바 작업 csv 문서 유 니 버 설 도구 클래스텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.