LoginSignup
9

More than 5 years have passed since last update.

AndroidでBitmapを画像のバイトサイズを指定してリサイズする

Posted at

画像の縦横のサイズを指定したリサイズは結構見つかったのですが、画像のバイトサイズを指定してリサイズする方法があまりないようなので紹介します。

バイトサイズに応じて縦横のスケールを変更してリサイズします。
下記のような実装になります。

public static Bitmap resizeImage(Bitmap img, float toSize) {
    int size = img.getByteCount(); // Android 3.1以降でしか使用できない。getRowBytes() * getHeight() と同じ
    float scale = (float)Math.sqrt(toSize / (float)size);

    Matrix matrix = new Matrix();
    matrix.postScale(scale, scale);

    return Bitmap.createBitmap(img, 0, 0, img.getWidth(), img.getHeight(), matrix, true);
}

例えば、100バイトの画像を、25バイトにリサイズしたい場合(1/4にリサイズ)は、縦横の長さをそれぞれ半分にしています。

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
What you can do with signing up
9