This is the code I am using to get a full sized image, which is >2mb in size and 3560 X 1876 in dimension.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
image = (ImageView) findViewById(R.id.image);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
filePath = Environment.getExternalStorageDirectory() + "/Full_"
+ System.currentTimeMillis() + ".jpeg";
File file = new File(filePath);
Uri output = Uri.fromFile(file);
Intent i = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
i.putExtra(MediaStore.EXTRA_OUTPUT, output);
startActivityForResult(i, CAPTURE_IMAGE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap photo = BitmapFactory.decodeFile(filePath, options);
image.setImageBitmap(photo);
}
Is there a way to get the image of specific size, in my case a <100kb sized image of dimensions 480 x 320.
You can take a look at this blog post I wrote on how to get Images from device's camera Activity:
Guide: Android: Use Camera Activity for Thumbnail and Full Size Image
If you look at the end of the guide, you have this method:
public static Bitmap decodeSampledBitmapFromFile(String path, int reqWidth, int reqHeight)
{ // BEST QUALITY MATCH
//First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);
// Calculate inSampleSize, Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
options.inPreferredConfig = Bitmap.Config.RGB_565;
int inSampleSize = 1;
if (height > reqHeight)
{
inSampleSize = Math.round((float)height / (float)reqHeight);
}
int expectedWidth = width / inSampleSize;
if (expectedWidth > reqWidth)
{
//if(Math.round((float)width / (float)reqWidth) > inSampleSize) // If bigger SampSize..
inSampleSize = Math.round((float)width / (float)reqWidth);
}
options.inSampleSize = inSampleSize;
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(path, options);
}
you can provider there the required dimensions for your image output.
you have to use the inSampleSize from BitmapFactory.Options. Through it the decoder will downsample your image of the inSampleSize. For instance inSampleSize = 2 will create a bitmap of width/2 and heigth/2
int destWidth = 480;
int destHeight = 320;
while ( (bitmapWidth/2 > destWidth)
|| (bitmapHeight/2 > destHeight)) {
++inSampleSize;
bitmapWidth /= 2;
bitmapHeight /=2;
}
What if using a simplest way to do it. Copy this method, pass your bitmap and required height and width, get a scaled image back :)
public static Bitmap resizeBitmap(Bitmap originalBitmap, int width, int height) {
float scaleWidth = ((float) width) / originalBitmap.getWidth();
float scaleHeight = ((float) height) / originalBitmap.getHeight();
Matrix matrix = new Matrix();
matrix.postScale(scaleWidth, scaleHeight);
return Bitmap.createBitmap(originalBitmap, 0, 0, original.getWidth(),original.getHeight(), matrix, true);
}
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
From the logcat I understand that the Activity crashes because of NullPointerException causes by this line of code.
mImageView.setImageBitmap(decodeSampledBitmapFromResource(getResources(),
R.id.picture, imageWidth, imageHeight));
I have read articles about similar problem but still getting NullPointerException. I think that mistake right under my nose, but still I can't catch it.
Where should I put this line to avoid NullPointerException?
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
ImageView mImageView = (ImageView) findViewById(R.id.picture);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(getResources(), R.id.picture, options);
int imageHeight = options.outHeight;
int imageWidth = options.outWidth;
mImageView.setImageBitmap(decodeSampledBitmapFromResource(getResources(),
R.id.picture, imageWidth, imageHeight));
}
public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId,
int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(res, resId, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeResource(res, resId, options);
}
public static int calculateInSampleSize(
BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) > reqHeight
&& (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
and here is ImageView from layout.
<ImageView
android:layout_height="240dp"
android:layout_width="199dp"
android:src="#drawable/galaxy"
android:id="#+id/picture"
android:layout_gravity="center_horizontal"
android:scaleType="fitCenter"
android:layout_weight="0.19" />
There is a cleaner alternative to display a bitmap onto a imageview.
Try this:
private Bitmap bitmap_image;
Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//get image from resources
bitmap_image = BitmapFactory.decodeResource(getResources(), R.drawable.picture);
ImageView mImageView = (ImageView) findViewById(R.id.picture);
mImageView.setImageBitmap(bitmap_image);
}
-To retrieve a image from resources and store it into a bitmap, use BitmapFactory.decodeResource(getResources(), R.drawable.yourimagename);
-at this point you can directly set the image to a imageView. If you want to manipulate the size of the image here is a function that will resize a bitmap:
public Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth) {
int width = bm.getWidth();
int height = bm.getHeight();
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
// CREATE A MATRIX FOR THE MANIPULATION
Matrix matrix = new Matrix();
// RESIZE THE BIT MAP
matrix.postScale(scaleWidth, scaleHeight);
// RECREATE THE NEW BITMAP
Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, false);
return resizedBitmap;
}
-If you need clarification on the re-sizing of the bitmap, refer to this stackoverflow post:
How to Resize a Bitmap in Android?
-if you need a full working example, i have a activity that utilizes retrieving a image from resources and storing it into a bitmap and then displaying it on screen. The only part I do not have that you request, is displaying the bitmap in a imageView.
Github class link:
https://github.com/Rifat-Rashid/thePlatformer/blob/master/MainActivity.java
My App have an activity with a ImageView where i pick a picture from phone gallery and set in this ImageView as user's profile picture.
My problem is that some pictures when picked make app stop cause is too big, i want to know if someone can look my code and help me how can i resize this picked picture, so after set in this image view, how can user cut this picture before set, here below is my code where i pic the picture. i will be so greatful if someone do the needed changes and give me the code cause i dont know so much about developing. thank you.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
PreferenceManager.getDefaultSharedPreferences(this).edit().putString("picturePath", picturePath).commit();
cursor.close();
ImageView imageView = (ImageView) findViewById(R.id.User);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}
Try this is image compression like whtsapp I have used in my application https://www.built.io/blog/2013/03/improving-image-compression-what-weve-learned-from-whatsapp/
You can use Picasso library. Get it from here.
The syntax looks like this:
Picasso.with(getContext()).load(imagePath).into(imageView);
Not gonna rewrite your code but this could be useful
Bitmap bitmap = BitmapFactory.decodeFile(foto.getFotoOrderFilePath());
Double height = (double)bitmap.getHeight();
Double scalingFactor = (960.0/height);
int tempWidht = bitmap.getWidth();
Double Dwidth = (tempWidht*scalingFactor);
int width = Dwidth.intValue();
Log.v("bitmap dimensions: ", String.valueOf(height) + " + " +String.valueOf(width) + " + " + String.valueOf(scalingFactor));
bitmap = Utilities.scaleBitmap(bitmap, width, 960);
An excerpt from code I use to scale a bitmap down. It sets the hight to 960 and get the scaling to change the width accordingly.
edit:
the ScaleBitmap method.
public static Bitmap scaleBitmap(Bitmap bitmap, int wantedWidth, int wantedHeight) {
Bitmap output = Bitmap.createBitmap(wantedWidth, wantedHeight, Config.ARGB_8888);
Canvas canvas = new Canvas(output);
Matrix m = new Matrix();
m.setScale((float) wantedWidth / bitmap.getWidth(), (float) wantedHeight / bitmap.getHeight());
canvas.drawBitmap(bitmap, m, new Paint());
return output;
}
sorry for the late response
You can try this code to resize image as per your requirement
public Bitmap decodeSampledBitmapFromResource(String Filepath,
int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(Filepath, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(Filepath, options);
}
public int calculateInSampleSize(
BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
int inSampleSize = 1;
final int height = options.outHeight;
final int width = options.outWidth;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) > reqHeight
&& (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
check here
http://developer.android.com/training/displaying-bitmaps/load-bitmap.html
What i'm doing/trying to do, is.
1. Take a photo
2. Save it
3. Load/display it into a Bitmap
Opening the Built in camera application:
public void openCamera() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File file = new File(Environment.getExternalStorageDirectory()+ File.separator + "image.jpg");
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
onActivityResult:
protected void onActivityResult(int requestCode, int resultCode, Intent data){
//Check that request code matches ours:
if (requestCode == REQUEST_IMAGE_CAPTURE){
//Get our saved file into a bitmap object:
File file = new File(Environment.getExternalStorageDirectory()+File.separator + "image.jpg");
Bitmap image = decodeSampledBitmapFromFile(file.getAbsolutePath(), 1000, 700);
}
}
decodeSamoleBitmapFromFile:
public static Bitmap decodeSampledBitmapFromFile(String path, int reqWidth, int reqHeight)
{ // BEST QUALITY MATCH
//First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);
// Calculate inSampleSize, Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
options.inPreferredConfig = Bitmap.Config.RGB_565;
int inSampleSize = 1;
if (height > reqHeight)
{
inSampleSize = Math.round((float)height / (float)reqHeight);
}
int expectedWidth = width / inSampleSize;
if (expectedWidth > reqWidth)
{
//if(Math.round((float)width / (float)reqWidth) > inSampleSize) // If bigger SampSize..
inSampleSize = Math.round((float)width / (float)reqWidth);
}
options.inSampleSize = inSampleSize;
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(path, options);
}
I was hoping for it to load it into a bitmap. If anyone could point me in the right direction that would be very helpful!
In order to display a Bitmap, you'll have to use an ImageView. Once you have both the bitmap and the reference to your ImageView, call ImageView.setImageBitmap(Bitmap) to display your bitmap.
I am using native camera in my app. And after taking picture I am showing it to user on next activity in the Imageview. Now the problem is, when I save picture taken by front camera, the picture shows up in the next activity's imageview but not in the case when taken by back camera.
I am going to next activity after taking picture in the following way:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
case REQUEST_CODE_HIGH_QUALITY_IMAGE:
Toast.makeText(getApplicationContext(),
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
Uri.parse("file://"
+ Environment.getExternalStorageDirectory())));
//refreshing gallery
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
mediaScanIntent.setData(mHighQualityImageUri);
sendBroadcast(mediaScanIntent);
Intent intentActivity = new Intent(MyCameraActivity.this,PhotoSortrActivity.class);
intentActivity.putExtra("data", mHighQualityImageUri);
Log.v("Uri before Sending",mHighQualityImageUri+"");
startActivity(intentActivity);
break;
default:
break;
}
}
and this where I am showing the captured image. :
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_photosortr);
this.setTitle(R.string.instructions);
image = (ImageView) findViewById(R.id.img_view);
InputStream iStream = null;
try {
iStream = getContentResolver().openInputStream(uri);
inputData = getBytes(iStream);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Bitmap cameraBitmap = BitmapFactory.decodeByteArray(inputData, 0, inputData.length);
Bitmap cameraScaledBitmap = Bitmap.createScaledBitmap(cameraBitmap, cameraBitmap.getWidth(), cameraBitmap.getHeight(), true);
Matrix matrix = new Matrix();
if(cameraScaledBitmap.getWidth()>cameraScaledBitmap.getHeight())
{
matrix = new Matrix();
matrix.postRotate(270);
}
// final Bitmap newImage = Bitmap.createBitmap(cameraScaledBitmap.getWidth(), cameraScaledBitmap.getHeight(), Bitmap.Config.ARGB_8888);
// ask the bitmap factory not to scale the loaded bitmaps
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inScaled = false;
Bitmap cameraScaledBitmap2 = Bitmap.createBitmap(cameraScaledBitmap, 0, 0, cameraScaledBitmap.getWidth(), cameraScaledBitmap.getHeight(), matrix, true);
// image.setImageURI(uri);
image.setImageBitmap(cameraScaledBitmap2);
BitmapDrawable bg = new BitmapDrawable(cameraScaledBitmap2);
// photoSorter.SetBackgroundFromUrl(data);
}
#Override
protected void onResume() {
super.onResume();
//photoSorter.loadImages(this);
}
#Override
protected void onPause() {
super.onPause();
//photoSorter.unloadImages();
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
//photoSorter.trackballClicked();
return true;
}
return super.onKeyDown(keyCode, event);
}
public byte[] getBytes(InputStream inputStream) throws IOException {
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
byteBuffer.write(buffer, 0, len);
}
return byteBuffer.toByteArray();
}
Here is my layout of second activity:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/fl_camera">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
>
<ImageView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:contentDescription="content_desc_overlay"
android:src="#drawable/ic_launcher"
android:id="#+id/img_view"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
/>
</RelativeLayout>
</FrameLayout>
Why it is not setting image in the Imageview when using backcamera whereas it is working when taken by front camera. please help me
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
public class ImageResizer {
public static Bitmap decodeSampledBitmapFromFile(String filename,
int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options
options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filename, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(filename, options);
}
public static int calculateInSampleSize(BitmapFactory.Options options,
int reqWidth, int reqHeight) {
// BEGIN_INCLUDE (calculate_sample_size)
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) > reqHeight
&& (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
// This offers some additional logic in case the image has a strange
// aspect ratio. For example, a panorama may have a much larger
// width than height. In these cases the total pixels might still
// end up being too large to fit comfortably in memory, so we should
// be more aggressive with sample down the image (=larger inSampleSize).
long totalPixels = width * height / inSampleSize;
// Anything more than 2x the requested pixels we'll sample down further
final long totalReqPixelsCap = reqWidth * reqHeight * 2;
while (totalPixels > totalReqPixelsCap) {
inSampleSize *= 2;
totalPixels /= 2;
}
}
return inSampleSize;
// END_INCLUDE (calculate_sample_size)
}
}
Usage of method
Bitmap bmp = ImageResizer.decodeSampledBitmapFromFile(new File(filePath).getAbsolutePath(), 512, 342);
This will resize your bitmap so that you can get rid from OOM error.process these inside UI thread which seems better.
Bitmap myBitmap = BitmapFactory.decodeFile(mediaFile.getAbsolutePath());
int height = (myBitmap.getHeight() * 512 / myBitmap.getWidth());
Bitmap scale = Bitmap.createScaledBitmap(myBitmap, 512, height, true);
// Here mediaFile is path of image.
// display scale bitmap to your ImageView
I am displaying an image in full screen mode,but whenever going to display large image then nothing display in the image view. Below code try to resize bitmap but got same result blank imageview.
public static Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth) {
int width = bm.getWidth();
int height = bm.getHeight();
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
Matrix matrix = new Matrix();
// RESIZE THE BIT MAP
matrix.postScale(scaleWidth, scaleHeight);
// RECREATE THE NEW BITMAP
Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height,
matrix, false);
return resizedBitmap;
}
You solve your problem from two mehtods
Method 1
call this method(function)
public Bitmap decodeImage(int resourceId) {
try {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeResource(getResources(), resourceId, o);
// The new size we want to scale to
final int REQUIRED_SIZE = 100; // you are free to modify size as your requirement
// Find the correct scale value. It should be the power of 2.
int scale = 1;
while (o.outWidth / scale / 2 >= REQUIRED_SIZE && o.outHeight / scale / 2 >= REQUIRED_SIZE)
scale *= 2;
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeResource(getResources(), resourceId, o2);
} catch (Throwable e) {
e.printStackTrace();
}
return null;
}
add this before your adapter
picture.setImageBitmap((decodeImage(item.drawableId));
instead of
picture.setImageResource(item.drawableId);
Mehtod 2
You need to adjust your image size. The better way is to decode the image to a bitmap, and set the bitmap to the ImageView. For example:
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inSampleSize = 4;
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), item.drawableId, opts);
picture.setImageBitmap (bitmap);
I had the same problem. Got is solved through the following code.
Provide the filepath, desired width and desired height to the method. For more reference see here
public static Bitmap decodeScaledBitmapFromSdCard(String filePath, int reqWidth,
int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(filePath, options);
}
public static int calculateInSampleSize(BitmapFactory.Options options,
int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
// Calculate ratios of height and width to requested height and width
final int heightRatio = Math.round((float) height / (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
// Choose the smallest ratio as inSampleSize value, this will guarantee
// a final image with both dimensions larger than or equal to the
// requested height and width.
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
}
return inSampleSize;
}
Probably the image size is too large that the system cannot allocate enough memory to load it.
you can try loading your image after scaling it it with BitmapFactory.Options sampleSize
check this link for more info
http://developer.android.com/training/displaying-bitmaps/load-bitmap.html
may be this will work for you
public static Bitmap decodeSampledBitmapFromResource(String pathName,
int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(pathName, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth,
reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(pathName, options);
}
public static int calculateInSampleSize(BitmapFactory.Options options,
int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and
// keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) > reqHeight
&& (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
You solve your problem in Fragment
Add method in adapter
public Bitmap decodeImage(int gridViewImageId) {
try {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeResource(mContext.getResources(), gridViewImageId, o);
// The new size we want to scale to
final int REQUIRED_SIZE = 100; // you are free to modify size as your requirement
// Find the correct scale value. It should be the power of 2.
int scale = 1;
while (o.outWidth / scale / 2 >= REQUIRED_SIZE && o.outHeight / scale / 2 >= REQUIRED_SIZE)
scale *= 2;
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeResource(mContext.getResources(), gridViewImageId, o2);
} catch (Throwable e) {
e.printStackTrace();
}
return null;
}
and add this line
imageViewAndroid.setImageBitmap(decodeImage(gridViewImageId[i]));