安卓设备无法从服务器加载图片

3

我正在尝试从服务器下载图像,但总是抛出异常。有人能告诉我为什么会发生这种情况,以及正确的方法是什么吗?

 public static String getBitmap(String url) throws IOException {

        InputStream is = (InputStream) new URL(url).getContent();
        Bitmap bmp= BitmapFactory.decodeStream(is);
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.JPEG, 100, stream);
        byte[] b=stream.toByteArray();
        String encoded = Base64.encodeToString(b, Base64.DEFAULT);


        is.close();
        return encoded;


}

请粘贴您正在收到的异常。 - Nayan Srivastava
你遇到了什么异常?使用这个 - Piyush
你能否发布一下你的异常堆栈跟踪信息? - Sandeep dhiman
最好使用PicassoGlide库来加载服务器图片。 - Piyush
3个回答

0
请尝试使用这些函数获取位图并下载位图。
Bitmap bitmap = getBitmapfromUrl(imageurl);
imageview.setImageBitmap(bitmap);

SaveImage(bitmap);

public Bitmap getBitmapfromUrl(String imageUrl) {
    try {
        URL url = new URL(imageUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.connect();
        InputStream input = connection.getInputStream();
        Bitmap bitmap = BitmapFactory.decodeStream(input);
        return bitmap;

    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return null;

    }
}

private void SaveImage(Bitmap finalBitmap) {

    String root = Environment.getExternalStorageDirectory().toString();
    File myDir = new File(root + "/saved_images");
    myDir.mkdirs();
    Random generator = new Random();
    int n = 10000;
    n = generator.nextInt(n);
    String fname = "Image-" + n;
    File file = new File(myDir, fname);
    if (file.exists()) file.delete();
    try {
        FileOutputStream out = new FileOutputStream(file);
        finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
        out.flush();
        out.close();

    } catch (Exception e) {
        e.printStackTrace();
    }
}

在你的清单文件中添加这个权限


@rashmi ranjan 请检查我的答案。在URL中获取图像并轻松保存图像。 - Ratilal Chopda

0

尝试使用 GlidePicasso 图像处理库。

  1. 这里是 Glide 演示
Glide.with(this).load(YourImageURL)
                .diskCacheStrategy(DiskCacheStrategy.SOURCE)
                 .into(Imageview);

并在gradle中添加此依赖项。

compile 'com.github.bumptech.glide:glide:3.7.0'

在图片加载时,您也可以设置占位符。就像HTML中的alt属性一样。

Glide.with(this).load(YourImageURL)
                    .diskCacheStrategy(DiskCacheStrategy.SOURCE)
                    .placeholder(R.drawable.backimage)
                    .into(Imageview);

这是 Picasso 演示。
   Picasso.with(context).load(url).placeholder(R.drawable.user_placeholder)
        .error(R.drawable.user_placeholder_error)
        .into(imageView);

并添加此依赖项:

compile 'com.squareup.picasso:picasso:2.5.2'

这些库还提供了缓存功能,因此您无需第二次加载。

但它总是抛出异常。有人能告诉我为什么会发生这种情况,正确的方法是什么吗?你没有回答问题。你的回答不是一个答案,而是一条建议。 - greenapps

0

从您的活动中调用此函数并获取输入流。在获取输入流之后(Bitmap bitmap = Bitmap.decodeStream(inputStream));)

private InputStream OpenHttpConnection(String urlString) throws IOException
    {
    InputStream in = null;
    int response = -1;

    URL url = new URL(urlString);
    URLConnection conn = url.openConnection();

    if (!(conn instanceof HttpURLConnection)) throw new IOException("Not an HTTP connection");

    try{
    HttpURLConnection httpConn = (HttpURLConnection) conn;
    httpConn.setAllowUserInteraction(false);
    httpConn.setInstanceFollowRedirects(true);
    httpConn.setRequestMethod("GET");
    httpConn.connect();

    response = httpConn.getResponseCode();
    if (response == HttpURLConnection.HTTP_OK) {
    in = httpConn.getInputStream();
    }
    }
    catch (Exception ex)
    {
    throw new IOException("Error connecting");
    }
    return in;
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接