簡體   English   中英

將網址轉換為位圖時獲取位圖為空

[英]Getting bitmap null while converting url to bitmap

我想從服務器下載圖像並將其轉換為位圖。 我試圖下載圖像並將其轉換為位圖,但它返回null。 我得到的位圖為空。

要將圖像轉換為位圖,我創建了一個asyncTask。

將網址傳遞給異步任務:

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);
                   }
                 }

怎么了

試試這個,我正在通過這種方法獲得圖像。

                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);

最可能的原因是您從服務器收到錯誤消息,或者無法解碼所獲取的數據。 首先,在連接打開后檢查響應代碼:

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

如果您得到的不是200,則表示檢索數據有問題(錯誤的url,auth或服務器錯誤)。 如果您確實得到200,則問題出在所接收的數據上。 將數據讀入字節數組並將其轉儲到文件中以進行檢查。

第一次檢查圖像是否確實存在,如@aman grover所說(如果可用),請使用Picasso Lib從URL下載圖像。

這是示例代碼

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();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM