SWT IMAGE的裁剪
public class ImageCut{
private static Log ImageCutLog = LogFactory.getLog(ImageCut.class);
@SuppressWarnings("unchecked")
public static Image readUsingImageReader(Display display, Image oldImage, int locax, int locay, int width, int height){
Image newImage = null;
// 取得圖片讀入器
byte[] outdata = new byte[0];
ByteArrayOutputStream out = new ByteArrayOutputStream();
ImageLoader imageLoader = new ImageLoader();
imageLoader.data = new ImageData[]{oldImage.getImageData()};
imageLoader.save(out, SWT.IMAGE_JPEG);
try {
outdata = out.toByteArray();
out.flush();
} catch (IOException e1) {
// TODO Auto-generated catch block
ImageCutLog.error(e1);
}finally{
try {
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
ByteArrayInputStream source = new ByteArrayInputStream(outdata);
Iterator readers = ImageIO.getImageReadersByFormatName("jpg");
ImageReader reader = (ImageReader)readers.next();
ImageInputStream iis;
try {
iis = ImageIO.createImageInputStream(source);
reader.setInput(iis, true);
} catch (IOException e2) {
// TODO Auto-generated catch block
ImageCutLog.error(e2);
return newImage;
}
// 取得裁剪圖片
ImageReadParam param = reader.getDefaultReadParam();
Rectangle rect = new Rectangle(locax, locay, width, height);
param.setSourceRegion(rect);
BufferedImage bi;
try {
bi = reader.read(0,param);
} catch (IOException e2) {
// TODO Auto-generated catch block
ImageCutLog.error(e2);
return newImage;
}
try {
byte[] outdatacut = new byte[0];
ByteArrayOutputStream outscale = new ByteArrayOutputStream();
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(outscale);
encoder.encode(bi);
try {
outdatacut = outscale.toByteArray();
outscale.flush();
} catch (IOException e1) {
// TODO Auto-generated catch block
ImageCutLog.error(e1);
}finally{
try {
outscale.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
ByteArrayInputStream incut = new ByteArrayInputStream(outdatacut);
newImage = new Image(display, incut);
} catch (Exception e) {
// TODO Auto-generated catch block
ImageCutLog.error(e);
}
return newImage;
}
public static void main(String[] args){
ImageLoader loader1 = new ImageLoader();
loader1.load("d://shell.JPG");
Image old = new Image(Display.getDefault(), loader1.data[0]);
Image news = readUsingImageReader(Display.getDefault(),old,100,100,100,100);
if(null != news){
ImageLoader loader2 = new ImageLoader();
loader2.data = new ImageData[]{news.getImageData()};
loader2.save("d://1123.jpg", SWT.IMAGE_JPEG);
}
}
}