利用 `Graphics.translate(x, y)` 平移繪圖原點,配合 `drawImage()` 將源圖片指定區域繪製到目標小圖。循環遍歷行列,生成 `Image[]` 數組。
public class ImageUtil {
public static Image[] splitImage(Image img, int rows, int cols) {
if (img == null) return null;
Image[] result = new Image[rows * cols];
int w = img.getWidth() / cols;
int h = img.getHeight() / rows;
for (int i = 0; i < result.length; i++) {
result[i] = Image.createImage(w, h);
Graphics g = result[i].getGraphics();
g.translate((-i % cols) * w, (-i / cols) * h);
g.drawImage(img, 0, 0, Graphics.LEFT | Graphics.TOP);
}
return result;
}
}
建議源圖寬高能被行列數整除,避免邊緣截斷。