Load large Bitmap efficiently for dynamic image pick from gallery? - android

I want to load large Bitmap image in the Imageview.I am follow the code from Loading Large Bitmaps Efficiently .It's shown for single imageView.But I want to pick images from gallery for dynamic ImageView.I try to get the id of the picked Image and set decodeSampledBitmapFromResouce.It's set the Empty in the ImageView.Please help me to solve the Issue.Any help I'm very appreciated.Please see my code Below.
Button loadImg;
ImageView myImageView;
InputStream imageStream;
Bitmap productIndex = null;
private static int RESULT_LOAD_IMAGE = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loadImg = (Button)findViewById(R.id.btnPickImage);
myImageView = (ImageView) findViewById(R.id.myImgView);
loadImg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent,RESULT_LOAD_IMAGE);
}
});
}
#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);
cursor.close();
myImageView = (ImageView) findViewById(R.id.myImgView);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(picturePath, options);
int imageHeight = options.outHeight;
int imageWidth = options.outWidth;
String imageType = options.outMimeType;
// here I set the bitmap to ImageView but the Image is not shown
int picId = getResources().getIdentifier(picturePath, "drawable", getApplicationContext().getPackageName());
myImageView.setImageBitmap(decodeSampledBitmapFromResource(getResources(),picId,100,100));
}
}
public static int calculateInSampleSize(BitmapFactory.Options options,int reqWidth,int reqHeight) {
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;
while ((halfWidth / inSampleSize) > reqWidth && (halfHeight / inSampleSize) > reqHeight) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
public static Bitmap decodeSampledBitmapFromResource(Resources res,int resId,int reqWidth,int reqHeight) {
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(res,resId,options);
/* Calculate inSampleSize */
options.inSampleSize = calculateInSampleSize(options,reqWidth,reqHeight);
options.inJustDecodeBounds = false;
return BitmapFactory.decodeResource(res,resId,options);
}

Try this.
public static Bitmap decodeSampledBitmapFromFile(File f, int reqWidth, int reqHeight) { // BEST QUALITY MATCH
String path = f.getAbsolutePath();
// 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 background
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) {
inSampleSize = Math.round((float) width / (float) reqWidth);
}
options.inSampleSize = inSampleSize;
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
// Correct rotation
ExifInterface exif = null;
try {
exif = new ExifInterface(f.getPath());
} catch (IOException e) {
e.printStackTrace();
}
int rotation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
int rotationInDegrees = exifToDegrees(rotation);
Matrix matrix = new Matrix();
if (rotation != 0f) {
matrix.preRotate(rotationInDegrees);
}
Bitmap output = BitmapFactory.decodeFile(path, options);
if (output != null) {
return Bitmap.createBitmap(output, 0, 0, output.getWidth(), output.getHeight(), matrix, false);
} else {
return null;
}
}
public static int exifToDegrees(int exifOrientation) {
if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_90) {
return 90;
} else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_180) {
return 180;
} else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_270) {
return 270;
}
return 0;
}

Related

Android Imageview FITXY Image shrinking issue

`Hi All, I would like to pick an image from my phone gallery and show it as a background of a imageview.I am able to show it and even I am able to make the image fit whole screen via(FITXY property of imageview).
The issue is image actually shrinks , so I tried Fitcenter and adjustviewbounds property etc and all other properties but no luck , with this properties image fits center and I can see some gaps in(width and height).
Could any one help me on how to fix this issue.
Here is my full code and screenshots for references.
<FrameLayout
android:id="#+id/fm"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:background="#70b29c"
xmlns:android="http://schemas.android.com/apk/res/android">
<ImageView
android:id="#+id/set"
android:contentDescription="#string/hello_world"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:adjustViewBounds="true"/>
Here is my java code:
public class MainActivity extends Activity {
private static int RESULT_LOAD_IMAGE = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sc = (LinearLayout) findViewById(R.id.home);
Button wal = (Button) findViewById(R.id.setwall);
wal.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
});
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// check if the request code is same as what is passed here it is 2
if (requestCode == RESULT_LOAD_IMAGE && resultCode ==RESULT_OK && null != data) {
Uri picUri = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(picUri,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
filePath = cursor.getString(columnIndex);
cursor.close();
bitmapView = (ImageView) findViewById(R.id.set);
bitmapView.setImageBitmap(ExifUtils.rotateBitmap(filePath, decodeSampledBitmap(new File(filePath), 400, 800)));
bitmapView.setScaleType(ImageView.ScaleType.FIT_XY);
SharedPreferences shre = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
SharedPreferences.Editor edit = shre.edit();
edit.putString("profilePic", filePath);
edit.commit();
}
}
public Bitmap decodeSampledBitmap(File res, int reqWidth, int reqHeight) {
if (res != null) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
try {
FileInputStream stream2 = new FileInputStream(res);
BitmapFactory.decodeStream(stream2, null, options);
stream2.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// Calculate inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
o2.inJustDecodeBounds = false;
FileInputStream stream = null;
try {
stream = new FileInputStream(res);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Bitmap bitmap = BitmapFactory.decodeStream(stream, null, o2);
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
return bitmap;
} else
return null;
}
public 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;
}
}
Link for the screenshot here
Using FITXY will fit your image to the imageView regardless of the resolution or aspect ratio of image which will result in inappropriate display of image...
If you want your image to be displayed on the whole screen its better to use CENTER or CENTERCROP which will crop the selected image but set it in image's aspect ratio and will fully cover your view....

Image shown when taken by front camera but not visible when taken by Back camera

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

unable to add image to imageview from camera capture

I am developing one application in which I have to capture image from camera and add to ImageView. Here I have a problem while showing image on ImageView. If I click save button the image is not showing on ImageView for the first time,but for second time it is showing,please solve my problem, I am unable to find solution for this.
Code Snippet:
fromCamera.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
/* Log.e("OPEN", "CAMERA");
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(android.os.Environment
.getExternalStorageDirectory(), "temp.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivityForResult(intent, RESUL_CameraT_LOAD_IMAGE);*/
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
File file = new File(Environment.getExternalStorageDirectory()+File.separator +
"fav.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
startActivityForResult(intent, RESUL_CameraT_LOAD_IMAGE);
uploadalertDialog.dismiss();
}
});
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Uri selectedImage = null;
Bitmap bitmap;
try {
switch (requestCode) {
case RESUL_CameraT_LOAD_IMAGE:
if (resultCode == Activity.RESULT_OK) {
// imageView.setImageResource(android.R.color.transparent);
Log.e("GET IMAGE", "PATH");
try{
File file = new File(Environment.getExternalStorageDirectory()+File.separator
+ "fav.jpg");
bitmap = decodeSampledBitmapFromFile(file.getAbsolutePath(), 300, 300);
uloadImgView.setImageBitmap(bitmap);
ByteArrayOutputStream byteArray = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 90,
byteArray);
byte[] byte_arr = byteArray.toByteArray();
base64 = Base64.encodeToString(byte_arr, Base64.DEFAULT);
}
catch(Exception e){
e.printStackTrace();
}
}
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);
}
First of all add the following permission in you app's manifest file
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Then check the following code which I used in my application to set s user's profile pic.
// on click listener for the camera trigger
image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent cameraintent = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraintent, 101);
}
});
//onActivityResult
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Uri selectedImage = null;
Bitmap bitmap;
try {
switch (requestCode) {
case 101:
if (resultCode == Activity.RESULT_OK) {
if (null != data) {
selectedImage = data.getData(); // the uri of the image
// taken
bitmap = decodeSampledBitmapFromUri(this,
selectedImage, 100, 100);
image.setImageBitmap(bitmap);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
super.onActivityResult(requestCode, resultCode, data);
}
//Bitmap sampling
public static Bitmap decodeSampledBitmapFromUri(Activity callingActivity,
Uri uri, int reqWidth, int reqHeight) {
try {
InputStream input = callingActivity.getContentResolver()
.openInputStream(uri);
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
options.inSampleSize = 2; // make the bitmap size half of the
// original one
BitmapFactory.decodeStream(input, null, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth,
reqHeight);
input.close();
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
input = callingActivity.getContentResolver().openInputStream(uri);
Bitmap bitmap = BitmapFactory.decodeStream(input, null, options);
return bitmap;
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
} catch (IOException e) {// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
//calculate sample size
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;
}

BitmapFactory.decodeStream returns null if the handled image is greater than 6 mb on Android 2.2 device

in my App I need to scale an image, this works with normaly. But when a big pictured will be
loaded then the decodeStream method returns null. Currently it does not work when the image was bigger than 6 MB (5616x3744)
Does someone know why this happens and what can i do to fix this?
public static Bitmap scaleImage(final String filepath, int height, int width) throws IOException{
if (filepath == null){
Log.e(TAG, "cannot create Thumbnail without file");
return null;
}
File f = new File(filepath);
InputStream is = new FileInputStream(f);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeStream(is, null, options);
is.close();
final int imageHeight = options.outHeight;
final int imageWidth = options.outWidth;
String imageType = options.outMimeType;
final int thumbnailHeight = height;
final int thumbnailWidth = width;
int heightRatio = Math.round((float) imageHeight) / Math.round((float) thumbnailHeight);
int widthRatio = Math.round((float) imageWidth) / Math.round((float) thumbnailWidth);
int inSampleSize = 0;
if (heightRatio < widthRatio){
inSampleSize = heightRatio ;
}
else{
inSampleSize = widthRatio;
}
options.inSampleSize = inSampleSize;
// Decode bitmap with inSampleSize set
int retrySteps = 0;
InputStream is2 = new FileInputStream(f);
Bitmap bmp = null;
for (int i = 0; i < 5; i++){
options.inJustDecodeBounds = false;
try {
bmp = BitmapFactory.decodeStream(is2, null, options);
if (bmp != null){
i = 10;
}
else{
System.gc();
SystemClock.sleep(i * 1000);
options.inSampleSize = inSampleSize + 1;
}
} catch (OutOfMemoryError e) {
System.gc();
SystemClock.sleep(i * 1000);
}
}
is2.close();
return bmp;
thanks

ImageView can't load image(jpg,png,...)

I'm trying to load an image from my res/drawable folder.I used the guide from Android Developers Link.
For some reason it isnt working.The only error I get is "SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length",which I researched.Appearently it has to do with custom keyboards but I'm not using text input at all.The app itself isnt crashing.I hope you guys can help me :)
The layout file just contains a RelativeLayout with an ImageView.
public class PixelActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pixel);
String uri = "#drawable-hdpi/testbild.png";
final int imageResource = getResources().getIdentifier(uri, null, getPackageName());
final ImageView iv = (ImageView) findViewById(R.id.imageview1);
//int imageHeight = options.outHeight;
//int imageWidth = options.outWidth;
//String imageType = options.outMimeType;
new Thread(new Runnable()
{
public void run()
{
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(getResources(), imageResource, options);
iv.post(new Runnable()
{
public void run()
{
iv.setImageBitmap(decodeSampledBitmapFromResources(getResources(),imageResource,iv.getWidth(),iv.getHeight()));
//iv.setImageResource(R.drawable.testbild);
}
});
}
});
}
public static int calculateInSampleSize(BitmapFactory.Options options,int reqWidth, int reqHeight)
{
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if(height > reqHeight || width > reqWidth)
{
final int heightRatio = Math.round((float)height/(float)reqHeight);
final int widthRatio = Math.round((float)width/(float)reqWidth);
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
}
return inSampleSize;
}
public static Bitmap decodeSampledBitmapFromResources(Resources res, int resId, int reqWidth, int reqHeight)
{
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(res, resId, options);
options.inSampleSize = calculateInSampleSize(options,reqWidth,reqHeight);
options.inJustDecodeBounds = false;
return BitmapFactory.decodeResource(res, resId, options);
}
}
String uri = "#drawable-hdpi/testbild.png";
That is invalid. Delete the -hdpi portion and the .png portion, and try again. Or, switch to providing all three parameters to getIdentifier():
final int imageResource = getResources().getIdentifier("testbild", "drawable", getPackageName());

Categories

Resources