2016-07-02 3 views
0

Я пытаюсь загрузить изображение с URL-адреса с помощью picasso. Но я не могу сделать. Я трачу время на это более двух дней. Я попытался выполнить асинхронную задачу, которая также потерпела неудачу. я много пробовал. Пожалуйста, помогите мне.Как скачать изображение с url с помощью picasso

protected static void postNotification(Intent intentAction, Context context,String msg,String url){ 

    NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); 
    PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intentAction, Notification.DEFAULT_LIGHTS | Notification.FLAG_AUTO_CANCEL); 
    /* ImageDownloaderTask image = new ImageDownloaderTask(); 
    image.execute(url);*/ 
    Bitmap bitmapImage = retriveImage(url,context); //here only i want get that image. 
    Log.d("Bitmap", String.valueOf(bitmapImage));//Its print only null 
    Notification notification = new NotificationCompat.Builder(context) 
      .setSmallIcon(R.drawable.tapn) 
      .setContentTitle("Welcome!") 
      .setContentText(msg) 
      .setStyle(new NotificationCompat.BigPictureStyle().bigPicture(bitmapImage)) 
      .setContentIntent(pendingIntent) 
      .setDefaults(Notification.DEFAULT_SOUND) 
      .setAutoCancel(true) 
      .getNotification(); 

    mNotificationManager.notify(R.string.notification_number, notification); 
} 

private static Bitmap retriveImage(String url,Context c) { 
    CacheTarget cacheTarget = new CacheTarget(); 
    Picasso.with(c) 
      .load(url) 
      .into(cacheTarget); 
    return cacheTarget.getCacheBitmap(); 
} 

private static class CacheTarget implements Target { 
    private Bitmap cacheBitmap; 
    @Override 
    public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from)  { 
     cacheBitmap = bitmap; 
    } 

    @Override 
    public void onBitmapFailed(Drawable errorDrawable) { 

    } 

    @Override 
    public void onPrepareLoad(Drawable placeHolderDrawable) { 

    } 
    public Bitmap getCacheBitmap() { 
     return cacheBitmap; 
    } 
} 

Заранее благодарен!

+2

Возможного дубликата [Загрузка изображений Использования Picasso] (http://stackoverflow.com/questions/27729976/download- и-save-images-using-picasso) –

+0

Thats different question .. – hikoo

+0

ответы на этот вопрос также дают ответ на ваш вопрос .. Это просто, что ListView - это предмет доступа в этом вопросе. Но это не имеет значения поскольку основная цель - загрузить изображения. !! –

ответ

0

Попробуйте это:

// Define where you want to save the file 
String dirName = Environment.getExternalStorageDirectory().toString() + "/myAppData/images";  
final File storageDir = new File(dirName); 
      // Create directory 
      if (!storageDir.exists()) { 
       storageDir.mkdirs(); 
      } 
      // Your image address. ex: "http://http://stackoverflow.com/myImages.jpg" 
      String MY_IMAGE_URL = "The image url that you wish to download"; 
       final ImageView profile = new ImageView(activity); 
       final String img_path = storageDir.getAbsolutePath() + "/" + "myimage.jpg"; 
       Picasso.with(activity).load(MY_IMAGE_URL).into(profile, new Callback() { 
        @Override 
        public void onSuccess() { 
         new Handler().postDelayed(new Runnable() { 
          @Override 
          public void run() { 
           // Save bitmap to local 
           Bitmap bitmap = ((BitmapDrawable)profile.getDrawable()).getBitmap(); 
           File file = new File(img_path); 
           try { 
            file.createNewFile(); 
            FileOutputStream ostream = new FileOutputStream(file); 
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, ostream); 
          ostream.close(); 
         } catch (IOException e) { 
         e.printStackTrace(); 
        } 
       } 
      },100); 
      } 
     @Override 
     public void onError() { 
     } 
}); 

Надеется, что это поможет :)

Смежные вопросы