|
最近抽空研究了一下有关PNG方面的东西(听说最近网上关于这个东西的讨论比较火)。再正式给出PNG研究心得之前,我先做个引线,把我接触过的三种读取资源文件的方法发上来,供大家讨论。如如果您有新的或是更好的方法,请一定要告诉我,我将十分感谢你(我的QQ:70705327)
下面就给出具体代码,与以往一样,我会在代码的适当位置使用注释。但我不会保证在我机器上可以运行的程序会在所有机器上运行(据说这可能是人品问题)。
import javax.microedition.lcdui.*; import java.io.*;
public class ImageCanvas extends Canvas { private Image byteImg; private InputStream input; public ImageCanvas() { try { jbInit(); } catch (Exception e) { e.printStackTrace(); } }
/** * 三种方法任选一种 * @throws Exception */ private void jbInit() throws Exception { byteImg = this.readImage("/res/pic.bin", 11110); // 从一个合成包里读取资源,如*.bin文件 //byteImg = Image.createImage("/res/caidan.png"); // 直接读取PNG文件 //byteImg = this.importImage(this.caiDanImage()); // 从byte数组里记取资源,将资源像素保存在byte数组中 System.out.println("内存情况: " + Runtime.getRuntime().freeMemory() + " / " + Runtime.getRuntime().totalMemory());//这种情况下会简单看下每种方法对内存的影响 //this.getByte("/res/caidan.png"); }
/** * Reads a file from the BIN file and return data as an Image * @param binfile String 文件名 * @param pos long 需要跳过的字节长度 * @return Image 返回一个Image对像 */ public Image readImage(String binfile, long pos) { byte buffer[]; int len; try { InputStream is = getClass().getResourceAsStream(binfile); is.skip(pos); len = (is.read() & 0xFF) << 24; // 如果不懂得这几句的意思,请留言给我,或是补习一下基本的编程知识 len |= (is.read() & 0xFF) << 16; len |= (is.read() & 0xFF) << 8; len |= (is.read() & 0xFF); buffer = new byte[len]; is.read(buffer, 0, buffer.length); is.close(); is = null; System.gc(); } catch (Exception e) { buffer = null; e.printStackTrace(); System.gc(); return null; } return Image.createImage(buffer, 0, buffer.length); }
/** * 将资源文件转换为byte数组 * @param file String 需要转换的文件名 */ private void getByte(String file) { byte[] myData = null; input = getClass().getResourceAsStream(file); try { ByteArrayOutputStream byteArray = new ByteArrayOutputStream(); int ch = 0; while ((ch = input.read()) != -1) { byteArray.write(ch); } for (int i = 0; i < byteArray.size(); i++) { myData = byteArray.toByteArray(); } for (int i = 0; i < myData.length; i++) { System.out.println(myData[i] + ","); } } catch (Exception e) {} //return myData; }
/** * 利用byte数据流生成图片 * @param byteFile byte[] 图片文件byte数据流 * @return Image 返回Image对象 */ private Image importImage(byte[] byteFile) { Image img = null; img = Image.createImage(byteFile, 0, byteFile.length); return img; }
protected void paint(Graphics g) { /** @todo Add paint codes */ g.setColor(0xffffff); g.fillRect(0, 0, this.getWidth(), this.getHeight()); g.drawImage(byteImg, 30, 30, g.TOP | g.LEFT); }
private byte[] xiangSuImage() { byte[] iCaiDanImage = { -119, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72, 68, 82, 0, 0, 0, 65, 0, 0, 0, 56, ......//未完的数据 }; return iCaiDanImage; }
}
总体来说,程序本身并没有难点,我只是想通过这篇文章来深入到PNG的研究当中,就像我们看到的,我们可以通过程序来操作PNG的基本元素(虽然本文中还没有),这其中可以包括PNG的四个基本数据块。这三种方法各有利弊,但竟世界上没有绝对完美的东西。 如果您对这方面感兴趣,请加我QQ:70705327 一起讨论。
|