无法在Android中从服务器加载图像

时间:2017-05-16 05:28:33

标签: java android

这里我试图从服务器下载图像。但它总是抛出异常。任何人都可以告诉我为什么会发生这种情况以及正确的方式是什么?

 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;


}

3 个答案:

答案 0 :(得分: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();
    }
}

并在清单文件中添加此权限

         

答案 1 :(得分:0)

尝试使用GlidePicasso图片处理库。

  1. 这里是Glide演示
  2. 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);
    
    1. 这是Picasso演示
    2.    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'
      

      这些lib还提供cache feature,因此您无需再次加载。

答案 2 :(得分:0)

从您的活动中调用此函数并获取inputStream。获取inputStream后(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;
    }