Java小项目之:拼图游戏!

Java小项目之:拼图游戏! 今天教大家用java做出一个拼图游戏,很适合java初学者练手。 所用素材: 部分代码:

package picture_mosical;
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 javax.imageio.ImageIO;

public class PictureCut {
	private static int width;// 切割后图片的宽度
	private static int height;// 切割后图片的高度
	private static String dir_name = "/CutImage";// 存放图片的文件夹名称

	public static void cut(String paths, int rows, int cols, String dir)
			throws Exception {
		Image img;
		ImageFilter new_if;//fasf你的
		BufferedImage bi = ImageIO.read(new File(paths));// 读取图像源
		if (bi == null) {
			System.out.println("图像源为空");
			return;
		}
		int baseWidth = bi.getWidth();// 读取图像源的宽度
		int baseHeight = bi.getHeight();// 读取图像源的高度
		width = baseWidth / cols;// 切割后图片的宽
		height = baseHeight / rows;// 切割后图片的高
		System.out.println("width:" + width + "		height:" + height);
		System.err.println("切割的行数=[" + rows + "]
切割的列数=[" + cols + "]");
		Image image = bi.getScaledInstance(baseWidth, baseHeight,
				Image.SCALE_DEFAULT);
		BufferedImage bimg;
		File file;
		int x = 0, y = 0;
		int index = 0;
		// 开始对图像源进行切割
		long s = Math.round(Math.random() * 8);
		System.out.println(s + ">>>>>>>>>>>>>>>");
		boolean flag = true;
		for (int i = 0; i < rows; i++) {
			y = (int) (i * height);
			for (int j = 0; j < cols; j++) {
				if (index == 8) {
					index=9;
					new_if = new CropImageFilter(0, 0, baseWidth, baseHeight);
					width=baseWidth;
					height=baseHeight;
					
				}else{
					x = (int) (j * width);
					new_if = new CropImageFilter(x, y, width, height);
				}

				
				
				img = Toolkit.getDefaultToolkit().createImage(
						new FilteredImageSource(image.getSource(), new_if));
				bimg = new BufferedImage(width, height,
						BufferedImage.TYPE_INT_RGB);
				Graphics gi = bimg.getGraphics();
				gi.drawImage(img, 0, 0, null);
				gi.dispose();
				file = new File(dir + index + ".jpg");
				ImageIO.write(bimg, "JPEG", file);

				index++;

			}
		}

	}

	public static void main(String[] args) {
		try {
			PictureCut.cut("src/picture_mosical/123.jpg", 3, 3,
					"WebRoot/images/");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
经验分享 程序员 微信小程序 职场和发展