EL比赛技术日志(4)
2012-03-29 16:31:35
=====================
这篇日志的意义非同小可啊,因为这是我的第一个原创实用程序。我们遇到问题时,总会上网找解决问题的软件,但当你找不到有特定功能的软件怎么办?自己编一个!
1.遇到的问题:在编游戏时,需要一张包含了角色各个方向行走的图片,像这样的图:【图】
这样当人物行走时只需顺序循环播放某一行的图片就行了。但是把一幅幅的单个动作拼成这一整张图却很不容易,因为即使photoshop这样的工具来做也非常繁琐,并且很难对齐,之前找了一个叫CorelDraw的排版工具,虽然可以排列,但背景无法做成透明的。找遍网络,没有合适软件。昨天晚上突发奇想,想到用java做一个这种软件太简单了!今天上机课不一会儿就编出来了哈哈
.下面给出源码。原创哦!
2.解决问题的程序
package cn.edu.nju.hx11;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JOptionPane;
public class ImageTools {
private int width, height, numPerRow, numPerColumn;
private BufferedImage outPng = null;
private BufferedImage inPng = null;
private Graphics gc = null;
public ImageTools() {
}
public void init() {
width = Integer.parseInt(JOptionPane.showInputDialog(null,
"请输入每幅图的宽度,以像素为单位"));
height = Integer.parseInt(JOptionPane.showInputDialog(null,
"请输入每幅图的高度,以像素为单位"));
numPerRow = Integer.parseInt(JOptionPane.showInputDialog(null,
"请输入目标图片每行的图数"));
numPerColumn = Integer.parseInt(JOptionPane.showInputDialog(null,
"请输入目标图片每列的图数"));
outPng = new BufferedImage(width * numPerRow, height * numPerColumn,
BufferedImage.TRANSLUCENT); //这里将图设置为透明背景
gc = outPng.getGraphics();
}
///ImageTools/res/image (1).png
public void makeOutPng() {
for (int i = 0; i < numPerColumn; i++) {
for (int j = 0; j < numPerRow; j++) {
try {
inPng = ImageIO.read(new File(System
.getProperty("user.dir")
+ "/resoure/image ("
+ (1 + j + i * numPerRow) + ").png"));
} catch (IOException e) {
// TODO Auto-generated catch block
System.exit(0);
}
gc.drawImage(inPng, (j * width), (i * height), null);
inPng = null;
}
}
}
public void saveOutPng() {
File file = new File(System.getProperty("user.dir") + "/out.png");
try {
ImageIO.write(outPng, "PNG", file);
} catch (IOException e) {
// TODO Auto-generated catch block
System.exit(0);
}
}
public void freeMemory() {
gc = null;
outPng = null;
}
public static void main(String[] args) {
while (true) {
ImageTools it = new ImageTools();
it.init();
it.makeOutPng();
it.saveOutPng();
it.freeMemory();
}
}
}
把要拼的图放到程序同一目录的resource目录下,把要拼的图全部选中然后重命名第一个为image按回车, 所有图片会被win7自动改为image (n)的形式,注意必须是此文件名,自己用就麻烦点吧呵呵,然后运行程序。
暂时比较简陋,但成功解决问题,拼出的图也非常整齐。符合自己使用的要求了,对一些异常的输入暂时不做处理,因为到这里已经能够完成任务,以后有时间把它做成一个完善的图片处理软件。
下面是拼出来的效果图,自己赞一个!【图】


浙公网安备 33010602011771号