圖片處理

改變大小

File picFile = new File("C:/pic/yui2.jpg");
FileOutputStream fos = new FileOutputStream(picFile);
BufferedOutputStream bos = new BufferedOutputStream(fos);

File picFileInput = new File("C:/pic/yui.jpg");
FileInputStream fis = new FileInputStream(picFileInput);
BufferedInputStream bis = new BufferedInputStream(fis);

BufferedImage bi = ImageIO.read(bis);
BufferedImage bo = new BufferedImage(512, 384,
BufferedImage.TYPE_INT_RGB);

Image image = bi.getScaledInstance(512, 384, Image.SCALE_REPLICATE);

bo.getGraphics().drawImage(image, 0, 0, null);
ImageIO.write(bo, "jpg", bos);
bos.close();
fos.close();


切割

/** *//**
* 圖像切割
* @param srcImageFile 源圖像地址
* @param descDir 切片目標文件夾
* @param destWidth 目標切片寬度
* @param destHeight 目標切片高度
*/
public static void cut(String srcImageFile, String descDir, int destWidth, int destHeight)
...{
try
...{
Image img;
ImageFilter cropFilter;
// 讀取源圖像
BufferedImage bi = ImageIO.read(new File(srcImageFile));
int srcWidth = bi.getHeight(); // 源圖寬度
int srcHeight = bi.getWidth(); // 源圖高度
if (srcWidth > destWidth && srcHeight > destHeight)
...{
Image image = bi.getScaledInstance(srcWidth, srcHeight, Image.SCALE_DEFAULT);
destWidth = 200; // 切片寬度
destHeight = 150; // 切片高度
int cols = 0; // 切片橫向數量
int rows = 0; // 切片縱向數量
// 計算切片的橫向和縱向數量
if (srcWidth % destWidth == 0)
...{
cols = srcWidth / destWidth;
}
else
...{
cols = (int) Math.floor(srcWidth / destWidth) + 1;
}
if (srcHeight % destHeight == 0)
...{
rows = srcHeight / destHeight;
}
else
...{
rows = (int) Math.floor(srcHeight / destHeight) + 1;
}
// 循環建立切片
// 改進的想法:是否可用多線程加快切割速度
for (int i = 0; i < rows; i++)
...{
for (int j = 0; j < cols; j++)
...{
// 四個參數分別爲圖像起點座標和寬高
// 即: CropImageFilter(int x,int y,int width,int height)
cropFilter = new CropImageFilter(j * 200, i * 150, destWidth, destHeight);
img = Toolkit.getDefaultToolkit().createImage(
new FilteredImageSource(image.getSource(), cropFilter));
BufferedImage tag = new BufferedImage(destWidth, destHeight, BufferedImage.TYPE_INT_RGB);
Graphics g = tag.getGraphics();
g.drawImage(img, 0, 0, null); // 繪製縮小後的圖
g.dispose();
// 輸出爲文件
ImageIO.write(tag, "JPEG", new File(descDir + "pre_map_" + i + "_" + j + ".jpg"));
}
}
}
}
catch (Exception e)
...{
e.printStackTrace();
}
}

發佈了14 篇原創文章 · 獲贊 1 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章