Last active
January 24, 2017 20:30
-
-
Save fatihsokmen/0da969b6ee089afa9f50d743f810c24d to your computer and use it in GitHub Desktop.
Generate thumbnail form image Uri
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.content.Context; | |
import android.graphics.Bitmap; | |
import android.graphics.BitmapFactory; | |
import android.net.Uri; | |
import java.io.IOException; | |
import java.io.InputStream; | |
public class BitmapResize { | |
public static Bitmap thumbnail(Context context, Uri uri, int minWidth, int minHeight) throws IOException { | |
InputStream inputStream = context.getContentResolver().openInputStream(uri); | |
final BitmapFactory.Options options = new BitmapFactory.Options(); | |
options.inJustDecodeBounds = true; | |
BitmapFactory.decodeStream(inputStream, null, options); | |
// Calculate inSampleSize | |
options.inSampleSize = calculateInSampleSize(options, minWidth, minHeight); | |
// close the input stream | |
inputStream.close(); | |
// reopen the input stream | |
inputStream = context.getContentResolver().openInputStream(uri); | |
// Decode bitmap with inSampleSize set | |
options.inJustDecodeBounds = false; | |
return BitmapFactory.decodeStream(inputStream, null, options); | |
} | |
public static int calculateInSampleSize(BitmapFactory.Options options, int requestedWidth, int requestedHeight) { | |
final int height = options.outHeight; | |
final int width = options.outWidth; | |
int inSampleSize = 1; | |
if (height > requestedHeight || width > requestedWidth) { | |
final int halfHeight = height / 2; | |
final int halfWidth = width / 2; | |
while ((halfHeight / inSampleSize) > requestedHeight | |
|| (halfWidth / inSampleSize) > requestedWidth) { | |
inSampleSize *= 2; | |
} | |
} | |
return inSampleSize; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment