หน้าเว็บ

วันพฤหัสบดีที่ 30 พฤษภาคม พ.ศ. 2556

java crop image



ImageUtils.java
package com.blogspot.na5cent.utils;

import java.awt.image.BufferedImage;

/**
 *
 * @author redcrow
 */
public class ImageUtils {

    public static BufferedImage crobImage(BufferedImage image, int startPointX, int startPointY, int width, int height) {
        int oldWidth = image.getWidth();
        int oldHeight = image.getHeight();

        if (startPointX < 0) {
            startPointX = 0;
        } else if (startPointX > oldWidth) {
            startPointX = oldWidth;
        }

        if (startPointY < 0) {
            startPointY = 0;
        } else if (startPointY > oldHeight) {
            startPointY = oldHeight;
        }

        if ((width + startPointX) > oldWidth) {
            width = oldWidth - startPointX;
        }

        if ((height + startPointY) > oldHeight) {
            height = oldHeight - startPointY;
        }

        return image.getSubimage(startPointX, startPointY, width, height);
    }
}
Test.java
package com.blogspot.na5cent.utils;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

/**
 *
 * @author redcrow
 */
public class Test {
    
    private static final String PATH = "C:\\Users\\Public\\Pictures\\Sample Pictures\\";

    public static void main(String[] args) throws IOException {
        BufferedImage bufferedImage = ImageIO.read(new File(PATH, "Chrysanthemum.jpg"));
        bufferedImage = ImageUtils.crobImage(bufferedImage, 100, 100, 200, 1000);
        ImageIO.write(bufferedImage, "png", new File(PATH, "Chrysanthemum2.jpg"));
    }
}

ไม่มีความคิดเห็น:

แสดงความคิดเห็น