0

我正在开发一个从服务器检索图像的黑莓应用程序,一些图像正在被检索,而其他图像在编码图像行中出现错误

            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;
}

我怎样才能解决这个问题以使所有图像都没有错误?

4

1 回答 1

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");
}
}
于 2012-06-07T04:43:11.920 回答