从服务器下载图片到android并在imageview中显示

新手上路,请多包涵

我有一个服务器(我使用 GlassFish)。我可以使用 http 将 Json 或 XML 等发送到我的 android 设备。我看到了一个将图片从我的 android 设备上传到服务器的示例。将我选择的图像转换为字节,转换为字符串并返回到我的服务器。所以我可以把它放在我的电脑(服务器)上。现在我只想要相反的东西:从我的 PC 获取图片并使用 URL 将图像(此处为位图)获取到 imageview。但调试 bmp 似乎是“空”。谷歌说这是因为我的图像不是有效的位图(所以我的服务器编码可能有问题?)。我需要对此代码进行哪些更改才能使其正常工作?

服务器代码:

 public class getImage{
    String imageDataString = null;

    @GET
    @Path("imageid/{id}")
    public String findImageById(@PathParam("id") Integer id) {
        //todo: schrijf een query voor het juiste pad te krijgen!
        System.out.println("in findImageById");
        File file = new File("C:\\Users\\vulst\\Desktop\\MatchIDImages\\Results\\R\\Tensile_Hole_2177N.tif_r.bmp");

        try{
            // Reading a Image file from file system
            FileInputStream imageInFile = new FileInputStream(file);
            byte imageData[] = new byte[(int) file.length()];
            imageInFile.read(imageData);

            // Converting Image byte array into Base64 String
            imageDataString = Base64.encodeBase64URLSafeString(imageData);
            imageInFile.close();

            System.out.println("Image Successfully Manipulated!");
        } catch (FileNotFoundException e) {
            System.out.println("Image not found" + e);
        } catch (IOException ioe) {
            System.out.println("Exception while reading the Image " + ioe);
        }
        return imageDataString;

    }

}

这是安卓端(安卓工作室):

 public class XMLTask extends AsyncTask<String, String, String> {

    @Override
    protected String doInBackground(String... urls) {
        HttpURLConnection connection = null;
        BufferedReader reader = null;
        try {
            java.net.URL url = new URL(urls[0]);
            connection = (HttpURLConnection) url.openConnection();
            connection.connect();
            InputStream stream = connection.getInputStream();
            reader = new BufferedReader(new InputStreamReader(stream));
            StringBuffer buffer = new StringBuffer();
            String line = "";
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }

            return buffer.toString();

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    @Override
    protected void onPostExecute(String line) {
        super.onPostExecute(line);
        byte[] imageByteArray = Base64.decode(line , Base64.DEFAULT);

        try {
            Bitmap bmp = BitmapFactory.decodeByteArray(imageByteArray, 0, imageByteArray.length);
            ivFoto.setImageBitmap(bmp);
        }catch (Exception e){
            Log.d("tag" , e.toString());
        }
    }
}

原文由 Axxeption 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 300
2 个回答

您尝试过 HttpURlConnection 吗?

这是一个示例代码:

 private class SendHttpRequestTask extends AsyncTask<String, Void, Bitmap> {
            @Override
            protected Bitmap doInBackground(String... params) {
                try {
                    URL url = new URL("http://xxx.xxx.xxx/image.jpg");
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setDoInput(true);
                    connection.connect();
                    InputStream input = connection.getInputStream();
                    Bitmap myBitmap = BitmapFactory.decodeStream(input);
                    return myBitmap;
                }catch (Exception e){
                    Log.d(TAG,e.getMessage());
                }
                return null;
            }

            @Override
            protected void onPostExecute(Bitmap result) {
                    ImageView imageView = (ImageView) findViewById(ID OF YOUR IMAGE VIEW);
                    imageView.setImageBitmap(result);
            }
    }

我希望我能帮忙

原文由 Melchizedek 发布,翻译遵循 CC BY-SA 3.0 许可协议

您可以使用 Glide 这是加载图像的最简单方法 这就是您保存图像的方法

Glide.with(context)
                        .load(image)
                        .asBitmap()
                        .into(new SimpleTarget<Bitmap>() {
                            @Override
                            public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {

                                String name = new Date().toString() + ".jpg";

                                imageName = imageName + name.replaceAll("\\s+", "");
                                Log.d(TAG, "onResourceReady: imageName = " + imageName);
                                ContextWrapper contextWrapper = new ContextWrapper(mContext);
                                File directory = contextWrapper.getDir("imageDir", Context.MODE_PRIVATE);

                                File myPath = new File(directory, imageName);

                                FileOutputStream fileOutputStream = null;
                                try {
                                    fileOutputStream = new FileOutputStream(myPath);
                                    resource.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                } finally {
                                    try {
                                        fileOutputStream.close();
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }
                        });

这就是您阅读图像的方式

ContextWrapper contextWrapper = new ContextWrapper(mContext);
    File directory = contextWrapper.getDir("imageDir", Context.MODE_PRIVATE);
    String path = directory.getAbsolutePath();
    path = path + "/" + imageName;
    Glide.with(mContext).load(path).into(your imageview);

原文由 Shashank Singh 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题