java圖片縮放剪切處理
package action;import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.awt.image.CropImageFilter;
import java.awt.image.FilteredImageSource;
import java.awt.image.ImageFilter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;import javax.imageio.ImageIO;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;public class ImageProcess {
/** * 對圖片進行縮放 * * @param srcImgFileName * @throws IOException */ public void zoomImage(String srcImgFileName) throws IOException { // 讀入文件 File _file = new File(srcImgFileName); // 構造Image對象 BufferedImage src = javax.imageio.ImageIO.read(_file); int width = src.getWidth(); int height = src.getHeight(); // 邊長縮小為二分之一 BufferedImage tag = new BufferedImage(width / 2, height / 2, BufferedImage.TYPE_INT_RGB); // 繪制縮小后的圖 tag.getGraphics().drawImage(src, 0, 0, width / 2, height / 2, null); FileOutputStream out = new FileOutputStream("D:\\test1\\targetIMG1-4.jpg"); JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); encoder.encode(tag); out.close(); // 邊長擴大為2倍 tag = new BufferedImage(width * 2, height * 2, BufferedImage.TYPE_INT_RGB); tag.getGraphics().drawImage(src, 0, 0, width * 2, height * 2, null); out = new FileOutputStream("D:\\test1\\targetIMGx2.jpg"); encoder = JPEGCodec.createJPEGEncoder(out); encoder.encode(tag); out.close(); } /** * 將圖片分成九塊 * * @param srcImageFile * @throws IOException */ public void cut(String srcImageFile) throws IOException { Image img; ImageFilter cropFilter; String dir = null; // 讀取源圖像 BufferedImage src = ImageIO.read(new File(srcImageFile)); int destWidth = src.getWidth() / 3; int destHeight = src.getHeight() / 3; // 循環 for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { // 四個參數分別為圖像起點坐標和寬高 cropFilter = new CropImageFilter(j * destWidth, i * destHeight, destWidth, destHeight); img = Toolkit.getDefaultToolkit().createImage(new FilteredImageSource(src.getSource(), cropFilter)); BufferedImage tag = new BufferedImage(destWidth, destHeight, BufferedImage.TYPE_INT_RGB); Graphics g = tag.getGraphics(); g.drawImage(img, 0, 0, null); // 繪制小圖 g.dispose(); // 輸出為文件 dir = "D:\\test1\\cut_image_" + i + "_" + j + ".jpg"; File f = new File(dir); ImageIO.write(tag, "JPEG", f); } } } public static void main(String[] args) throws IOException { String imgFileName = "D:\\test\\test.png"; ImageProcess iZoom = new ImageProcess(); iZoom.zoomImage(imgFileName); iZoom.cut(imgFileName); }
} </pre>
本文由用戶 fmms 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!