从黑莓字节中获取图像

时间:2012-06-06 15:26:05

标签: blackberry

我正在开发一个黑莓应用程序,它从服务器检索图像,一些图像正在被检索,其他图像在encodedImage行中给出错误

            ImageFromUrl _img = new ImageFromUrl(item.getThumbLink());
            byte[] bytes = _img.getbitmap();
            Bitmap newBitmap = new Bitmap(width, fieldHeight);
            if (bytes != null) {
                // bitmap = Bitmap.createBitmapFromBytes(bytes, 0,
                // bytes.length, Bitmap.SCALE_TO_FIT);
                EncodedImage image = EncodedImage.createEncodedImage(bytes,
                        0, bytes.length);
            }

这就是获取字节的连接

ImageFromUrl(String url) {
    this.url = url;
}

public byte[] getbitmap() {

    try {

        connection = (HttpConnection) Connector.open(
                url + Connection.getBlackBerryConnectionParams(),
                Connector.READ, true);

        InputStream is = connection.openInputStream();

        DataInputStream dis = new DataInputStream(is);
        ByteArrayOutputStream bStrm = new ByteArrayOutputStream();

        int ch;
        while ((ch = dis.read()) != -1) {
            // System.out.println((char) ch);
            // msg = msg + (char) ch;
            bStrm.write(ch);
        }
        dataArray = bStrm.toByteArray();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return dataArray;
}

如何解决这个问题才能让所有图像都没有错误?

1 个答案:

答案 0 :(得分:0)

试试这段代码:

public Bitmap getBitmapFromUrl(String url)
{
Bitmap bitmap=null;
try
{
    HttpConnection connection=(HttpConnection)Connector.open(url);
    connection.setRequestMethod(HttpConnection.GET);
    InputStream is=connection.openInputStream();
    int length=is.available();
    byte[] data=new byte[length];               
    data=IOUtilities.streamToBytes(is); 
    connection.close();
    is.close();
    bitmap=Bitmap.createBitmapFromBytes(data,0,data.length,1);
    if(bitmap!=null)
        return bitmap;
    else
        return bitmap=Bitmap.getBitmapResource("noimage.png");

}
catch (Exception e) 
{
    return bitmap=Bitmap.getBitmapResource("noimage.png");
}
}