get song album picture - Android android.database

Android examples for android.database:Cursor

Description

get song album picture

Demo Code

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.net.Uri;

public class Main {

  private static final Uri albumArtUri = Uri.parse("content://media/external/audio/albumart");
  static String TAG = "MediaUtil";

  public static Bitmap getArtwork(Context context, long song_id, long album_id, boolean small) {

    ContentResolver res = context.getContentResolver();
    Uri uri = ContentUris.withAppendedId(albumArtUri, album_id);
    if (uri != null) {
      InputStream in = null;/*from w  ww  .  jav  a 2 s  .c  o m*/
      try {
        in = res.openInputStream(uri);
        BitmapFactory.Options options = new BitmapFactory.Options();

        options.inSampleSize = 1;

        options.inJustDecodeBounds = true;

        BitmapFactory.decodeStream(in, null, options);
        if (small) {
          options.inSampleSize = computeSampleSize(options, 40);
        } else {
          options.inSampleSize = computeSampleSize(options, 600);
        }
        options.inJustDecodeBounds = false;
        options.inDither = false;
        options.inPreferredConfig = Bitmap.Config.ARGB_8888;
        in = res.openInputStream(uri);
        return BitmapFactory.decodeStream(in, null, options);

      } catch (FileNotFoundException e) {

      } finally {
        try {
          if (in != null) {
            in.close();
          }
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
    return null;
  }

  public static int computeSampleSize(Options options, int target) {
    int w = options.outWidth;
    int h = options.outHeight;
    int candidateW = w / target;
    int candidateH = h / target;
    int candidate = Math.max(candidateW, candidateH);
    if (candidate == 0) {
      return 1;
    }
    if (candidate > 1) {
      if ((w > target) && (w / candidate) < target) {
        candidate -= 1;
      }
    }
    if (candidate > 1) {
      if ((h > target) && (h / candidate) < target) {
        candidate -= 1;
      }
    }
    return candidate;
  }
}

Related Tutorials