yasushicohiのやんややんや

記事にするまでもないつぶやき、ありふれた想い、TIL。ブログ: https://yasushicohi.com

picassoで解像度が大きい画像を小さくする。

AndroidでImageViewに画像をはめ込む前に、もし大きい画像であれば縮小する必要があります。(レイアウトでの大きさに従って勝手にやってもらえます。) それが特にListとかに代入する場合は、OutOfMemoryで落ちます。(1000*1000の画像とかぐらい大きいと)

picassoにはTransformという機能があり、特別にクラスを作ることでinto()する前に画像を加工できます。 実装する機会があったので備忘録的にメモ程度に。

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import com.squareup.picasso.Transformation;

public class ResizeTransformation implements Transformation {
    Bitmap result;

    @Override
    public Bitmap transform(Bitmap source) {

        result = source;

        BitmapFactory.Options imageOption = new BitmapFactory.Options();
        imageOption.inJustDecodeBounds = true;
        int targetWidth = source.getWidth() / 4;
        int targetHeight = source.getHeight() / 4;

        if (source.getWidth() > 700 || source.getHeight() > 700) {
          // result = Bitmap.createBitmap(source, 0, 0, targetWidth, targetHeight, new Matrix(), true);
            result = Bitmap.createScaledBitmap(source, targetWidth, targetHeight,true);
            source.recycle();
            return result;
        }
        return source;
    }

    @Override public String key() { return "square()"; }
}