下面就給出具體代碼,與以往一樣,我會(huì)在代碼的適當(dāng)位置使用注釋。但我不會(huì)保證在我機(jī)器上可以運(yùn)行的程序會(huì)在所有機(jī)器上運(yùn)行(據(jù)說這可能是人品問題)。
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); // 從一個(gè)合成包里讀取資源,如*.bin文件
//byteImg = Image.createImage("/res/caidan.png"); // 直接讀取PNG文件
//byteImg = this.importImage(this.caiDanImage()); // 從byte數(shù)組里記取資源,將資源像素保存在byte數(shù)組中
System.out.println("內(nèi)存情況: " +
Runtime.getRuntime().freeMemory() +
" / " + Runtime.getRuntime().totalMemory());//這種情況下會(huì)簡單看下每種方法對(duì)內(nèi)存的影響
//this.getByte("/res/caidan.png");
}
/**
* Reads a file from the BIN file and return data as an Image
* @param binfile String 文件名
* @param pos long 需要跳過的字節(jié)長度
* @return Image 返回一個(gè)Image對(duì)像
*/
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; // 如果不懂得這幾句的意思,請(qǐng)留言給我,或是補(bǔ)習(xí)一下基本的編程知識(shí)
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);
}
/**
* 將資源文件轉(zhuǎn)換為byte數(shù)組
* @param file String 需要轉(zhuǎn)換的文件名
*/
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數(shù)據(jù)流生成圖片
* @param byteFile byte[] 圖片文件byte數(shù)據(jù)流
* @return Image 返回Image對(duì)象
*/
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,
......//未完的數(shù)據(jù)
};
return iCaiDanImage;
}
}
總體來
posted on 2011-05-19 08:37
Daniel 閱讀(398)
評(píng)論(0) 編輯 收藏 所屬分類:
CoreJava