【问题标题】:Getting bitmap null while converting url to bitmap将 url 转换为位图时获取位图 null
【发布时间】:2016-09-23 16:52:55
【问题描述】:

我想从服务器下载图像并将其转换为位图。我试图下载图像并将其转换为位图,但它返回 null。我得到位图为空。

为了将图像转换为位图,我创建了一个 asyncTask。

将 url 传递给异步任务:

String url = ServiceUrl.getBaseUrl() + ServiceUrl.getImageUserUrl() + profileImage;
            Log.e("url", url);


   new ImageUserTask(mContext, url, profileImage).execute();

ImageUserAsync 任务:

   public class ImageUserTask extends AsyncTask<Void, Void, Bitmap> {
    String imageprofile;
    private String url;
    private Bitmap mBitmap;
    private Context mContext;

    public ImageUserTask(Context context, String url, String imageprofile) {
        this.url = url;
       this.imageprofile = imageprofile;
        this.mContext = context;
    }

    @Override
    protected Bitmap doInBackground(Void... params) {
        try {
            //Url
            URL urlConnection = new URL(url);
            //Conntecting httpUrlConnection
            HttpURLConnection connection = (HttpURLConnection) urlConnection.openConnection();
            connection.setDoInput(true);
            //Connected to server
            connection.connect();
            //downloading  image
            InputStream input = connection.getInputStream();
            //converting image to bitmap
            Bitmap myBitmap = BitmapFactory.decodeStream(input);

            return myBitmap;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null; 
    }

    @Override
    protected void onPostExecute(Bitmap result) {
        super.onPostExecute(result);

        if (result != null) {


            result = mBitmap;

            new ImageServer(mContext).save(result);

        }
    }

}

编辑:

尝试使用毕加索:

        @Override
    protected void onPostExecute(JSONObject response) {
        super.onPostExecute(response);
        count=0;
        if (response.has("message")) {
            JSONObject userJson = null;
            String message = null;
            count++;
            try {

                if (response.getString("message").equalsIgnoreCase(KEY_SUCCESS)) {
                    Toast.makeText(mContext, "user authenticated successfully", Toast.LENGTH_LONG).show();
                    userJson = response.getJSONObject("user");
                    String userId = userJson.getString("user_id");
                    String userName = userJson.getString("user_name");
                    String profileImage = userJson.getString("profile_image");
                    String mobileNo = userJson.getString("mobile_no");


                    String url = ServiceUrl.getBaseUrl() + ServiceUrl.getImageUserUrl() + profileImage;
                    Log.e("url", url);

                    User user = new User();

                    user.setmUserId(userId);
                    user.setmUserName(userName);

                    user.setmProfileImage(profileImage);
                    user.setmMobileNo(mobileNo);

                    SharedPreferences.Editor editor = mContext.getSharedPreferences("username",mContext.MODE_PRIVATE).edit();
                    editor.putString("UserUsername",userName);
                    editor.commit();

                    Target target = new Target() {
                        @Override
                        public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {

                            try {

                                File f = new File(mContext.getCacheDir(), "Profile");
                                f.createNewFile();

//Convert bitmap to byte array
                                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                                bitmap.compress(Bitmap.CompressFormat.PNG, 0 /*ignored for PNG*/, bos);
                                byte[] bitmapdata = bos.toByteArray();

//write the bytes in file
                                FileOutputStream fos = new FileOutputStream(f);
                                fos.write(bitmapdata);
                                fos.flush();
                                fos.close();
                                Log.e("File",String.valueOf(f));
                            }
                            catch (IOException e)
                            {

                            }

                        }

                        @Override
                        public void onBitmapFailed(Drawable errorDrawable) {
                        }

                        @Override
                       public void onPrepareLoad(Drawable placeHolderDrawable) {
                        }
                    };

                        Picasso.with(mContext).load(url).into(target);


                    Toast.makeText(mContext, "user authenticated successfully", Toast.LENGTH_LONG).show();


                    progressDialog.dismiss();
                    mContext.startActivity(intent);
                    Picasso.with(mContext).cancelRequest(target);
                   }
                 }

怎么了?

【问题讨论】:

  • 发布您的 logcat 错误?
  • 如果图片真的存在,你检查过网址吗?
  • 我的第一个想法是记录传递给 ImageUserTask 的实际 URL。
  • 你可以使用毕加索。
  • 网址剂量存在。我也记录了网址。我得到了网址。它没有抛出任何异常。我做了调试,所以我知道了。 @AmanGrover

标签: java android bitmap


【解决方案1】:

试试这个我用这种方法获取图像。

                URL url1l = new URL("<Image url>");

                URLConnection connection = url1l.openConnection();
                connection.connect();
                // this will be useful so that you can show a typical 0-100% progress bar
                int fileLength = connection.getContentLength();

                // download the file
                InputStream is = new BufferedInputStream(connection.getInputStream());
                bitmap = BitmapFactory.decodeStream(is);

【讨论】:

【解决方案2】:

最可能的原因是您从服务器收到错误或您返回的数据无法解码。首先查看连接打开后的响应码:

connection.connect();
int respCode = connection.getResponseCode();
Log.d("resp code", "response code " + respCode);

如果您得到的不是 200,则说明检索数据有问题(错误的 url、auth 或服务器错误)。如果您确实得到 200,那么问题出在您收到的数据上。将数据读入字节数组并将其转储到文件中进行检查。

【讨论】:

    【解决方案3】:

    如@aman grover 所说,首先检查图像是否真的存在 如果可用,请使用Picasso Lib 从网址下载图片。

    这里是示例代码

    private Target target = new Target() {
          @Override
          public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
          //Note : here you can get Bitmap 
    
          }
    
          @Override
          public void onBitmapFailed(Drawable errorDrawable) {
          }
    
          @Override
          public void onPrepareLoad(Drawable placeHolderDrawable) {
          }
    }
    
    private void someMethod() {
       Picasso.with(this).load("url").into(target);
    }
    
    @Override 
    public void onDestroy() {  // could be in onPause or onStop
       Picasso.with(this).cancelRequest(target);
       super.onDestroy();
    }
    

    【讨论】:

    • 用户没有请求任何库帮助
    • @RahulKhurana 但是使用 picasso 比使用 Async Task 更好,这样他就可以轻松获得位图
    • 我尝试使用 picasso,但 bitmapLoaded 无法执行。 @pcpriyanka
    • 打印登录 onBitmapFailed 或 prepareLoad 并检查去向,如果可能,请提供您下载图片的 URL
    • 提供下载图片的网址
    猜你喜欢
    • 2018-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-24
    • 1970-01-01
    • 2017-02-27
    • 2011-12-20
    相关资源
    最近更新 更多