Android BinaryFactory.decodeStream始终返回null

时间:2014-04-22 11:05:25

标签: java android android-studio bitmapfactory

我正在尝试下载图像并使用BitmapFactory将其解码为位图,但decodeStream始终返回null。我搜索了许多类似的问题,尝试了很多例子,但没有找到解决方案。

这是我的代码:

    public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void downloadButton(View v)
    {
        String imageUrl = "http://www.picgifs.com/bird-graphics/bird-graphics/elf-owl/bird-graphics-elf-owl-527150.bmp";
        new Thread(new ImageDownloader(imageUrl)).start();
    }

    public void showImageButton(View v)
    {
        Bitmap image = ImageHandler.getImage();
        if (image == null)
            Log.e("Error", "No image available");
        else {
            ImageView imageView = (ImageView)findViewById(R.id.ImageView);
            imageView.setImageBitmap(image);
        }
    }
}

class ImageHandler
{
    static protected List<Bitmap> imagesList;
    static public void addImage(Bitmap image)
    {
        imagesList.add(image);
    }
    static public Bitmap getImage()
    {
        if (!imagesList.isEmpty())
            return imagesList.get(0);
        else
            return null;
    }
}

class ImageDownloader implements Runnable
{
    public Bitmap bmpImage;
    private String urlString;
    public ImageDownloader(String urlString)
    {
        this.urlString = urlString;
    }
    public void run()
    {
        try
        {
            AndroidHttpClient client = AndroidHttpClient.newInstance("Android");
            HttpGet getRequest = new HttpGet(urlString);
            HttpResponse response = client.execute(getRequest);
            HttpEntity entity = response.getEntity();
            InputStream inputStream = null;
            inputStream = (new BufferedHttpEntity(entity)).getContent();
            bmpImage = BitmapFactory.decodeStream(inputStream);
            //bmpImage = BitmapFactory.decodeStream(new URL(urlString).openConnection().getInputStream());
        }
        catch (Exception e)
        {
            Log.e("ImageDownloadError", e.toString());
            return;
        }
        if (bmpImage != null)
        {
            ImageHandler.addImage(bmpImage);
            Log.i("Info", "Image download successfully");
        }
        else
            Log.e("Error", "Bitmap is null");
    }
}

p.s showImageButton抛出IllegalStateException,但我已经厌倦了它。

2 个答案:

答案 0 :(得分:0)

我认为问题在于,一旦您使用了来自HttpUrlConnection的InputStream,您就无法倒回并再次使用相同的InputStream。因此,您必须为图像的实际采样创建新的InputStream。否则我们必须中止http请求。

只有当我们可以将输入流用于httprequest时,如果您尝试下载另一个图像,那么它将抛出一个错误,因为&#34;已经创建了InputStream&#34;像这样。所以我们需要在使用httpRequest.abort();

下载后中止httprequest

使用此:

HttpGet httpRequest = new HttpGet(URI.create(path) );
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = (HttpResponse) httpclient.execute(httpRequest);
HttpEntity entity = response.getEntity();
BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);
bmp = BitmapFactory.decodeStream(bufHttpEntity.getContent());
httpRequest.abort();

答案 1 :(得分:0)

根据我的观点,有两个理由

  1. 类ImageHandler无法获取图像
  2. android提出了从源代码中获取gif图像的问题。
  3. 我正在上传一份正常工作的代码,希望这能解决您的问题。

    MainActivity

     public class MainActivity extends Activity {
    
        private ProgressDialog progressDialog;
        private ImageView imageView;
        private String url = "http://www.9ori.com/store/media/images/8ab579a656.jpg";
        private Bitmap bitmap = null;
    
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            imageView = (ImageView) findViewById(R.id.imageView);
    
            Button start = (Button) findViewById(R.id.button1);
            start.setOnClickListener(new OnClickListener() {
    
                @Override
                public void onClick(View arg0) {
                    progressDialog = ProgressDialog.show(MainActivity.this,
                            "", "Loading..");
                    new Thread() {
                        public void run() {
                            bitmap = downloadBitmap(url);
                            messageHandler.sendEmptyMessage(0);
                        }
                    }.start();
    
                }
            });
        }
    
        private Handler messageHandler = new Handler() {
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                imageView.setImageBitmap(bitmap);
                progressDialog.dismiss();
            }
        };
    
        private Bitmap downloadBitmap(String url) {
            // Initialize the default HTTP client object
            final DefaultHttpClient client = new DefaultHttpClient();
    
            //forming a HttoGet request
            final HttpGet getRequest = new HttpGet(url);
            try {
    
                HttpResponse response = client.execute(getRequest);
    
                //check 200 OK for success
                final int statusCode = response.getStatusLine().getStatusCode();
    
                if (statusCode != HttpStatus.SC_OK) {
                    Log.w("ImageDownloader", "Error " + statusCode +
                            " while retrieving bitmap from " + url);
                    return null;
                }
    
                final HttpEntity entity = response.getEntity();
                if (entity != null) {
                    InputStream is = null;
                    try {
                        // getting contents from the stream
                        is = entity.getContent();
    
                        // decoding stream data back into image Bitmap
                        final Bitmap bitmap = BitmapFactory.decodeStream(is);
    
                        return bitmap;
                    } finally {
                        if (is != null) {
                            is.close();
                        }
                        entity.consumeContent();
                    }
                }
            } catch (Exception e) {
                getRequest.abort();
                Log.e(getString(R.string.app_name), "Error "+ e.toString());
            }
    
            return null;
        }
    }
    

    activity_main.xml中

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        tools:context=".MainActivity" >
    
        <Button
            android:id="@+id/button1"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_margin="15dp"
            android:text="Download Image" />
    
        <ImageView
            android:id="@+id/imageView"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:scaleType="centerInside"
            android:src="@drawable/ic_launcher" />
    
    </LinearLayout>
    

    并且也不要忘记在Manifest.xml文件中提供INTERNET权限