内存不足错误本机图像解码将图像加载到图库时出错

时间:2013-08-20 05:08:19

标签: java-me

我正在尝试将文件夹中的图像加载到我的应用程序中,我正在使用的代码是

FileConnection fc = null;
DataInputStream in = null;
DataOutputStream out = null;

try {
  fc = (FileConnection)Connector.open("file:///e:/Images/Abc.jpg");
  int length = (int)fc.fileSize();//possible loss of precision may throw error
  byte[] data = null;
  if (length != -1) {
    data = new byte[length];
    in = new DataInputStream(fc.openInputStream());
    in.readFully(data);
  }
  else {
    int chunkSize = 112;
    int index = 0;
    int readLength = 0;
    in = new DataInputStream(fc.openInputStream());
    data = new byte[chunkSize];
    do {
      if (data.length < index + chunkSize) {
        byte[] newData = new byte[index + chunkSize];
        System.arraycopy(data, 0, newData, 0, data.length);
        data = newData;
      }
      readLength = in.read(data, index, chunkSize);
      index += readLength;
    } while (readLength == chunkSize);
    length = index;
  }
  Image image = Image.createImage(data, 0, length);
  image = createThumbnail(image);
  ImageItem imageItem = new ImageItem(null, image, 0, null);
  mForm.append(imageItem);
  mForm.setTitle("Done.");
  fc = (FileConnection)Connector.open("file:///e:/Images/Abc.jpg");
  if(!fc.exists()){
      try{
      fc.create();                                                                                                                                                                              
      }catch(Exception ce){System.out.print("Create Error: " + ce);}
  }
  out = new DataOutputStream(fc.openOutputStream());
  out.write(data);
}
catch (IOException ioe) {
  StringItem stringItem = new StringItem(null, ioe.toString());
  mForm.append(stringItem);
  mForm.setTitle("Done.");
}
finally {
  try {
    if (in != null) in.close();
    if (fc != null) fc.close();
  }
  catch (IOException ioe) {}

希望它可能是图像的问题我试图调整图像大小

    private Image createThumbnail(Image image)
{
    int sourceWidth = image.getWidth();
    int sourceHeight = image.getHeight();
    int thumbWidth = 18;
    int thumbHeight = 23;

    Image thumb = Image.createImage(thumbWidth, thumbHeight);
    Graphics g = thumb.getGraphics();

    for (int y = 0; y < thumbHeight; y++)
    {
    for (int x = 0; x < thumbWidth; x++)
    {
    g.setClip(x, y, 1, 1);
    int dx = x * sourceWidth / thumbWidth;
    int dy = y * sourceHeight / thumbHeight;
    g.drawImage(image, x - dx, y - dy, Graphics.LEFT | Graphics.TOP);

    }
    }

    Image immutableThumb = Image.createImage(thumb);
    return immutableThumb;
} 

仍然会从memmory native image deocde错误中返回异常,有人请帮我解决它

1 个答案:

答案 0 :(得分:0)

这可能是因为两个原因。

  1. 图像尺寸:在某些手机中,由于堆码较小,设备无法加载图像,因此尝试使用较小的图像尺寸。

  2. 第二个原因可能是图片已损坏,请尝试使用其他图片。