I am using following method to get bitmap from url but image is not displayed. Image is a png file about 50x50px. Thank you.
public static Bitmap getBitmapFromURL(String src) {
try {
Log.e("src",src);
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeStream(input,null,options);
Log.e("Bitmap","returned");
//The new size we want to scale to
final int REQUIRED_SIZE=70;
//Find the correct scale value.
int scale=1;
while(options.outWidth/scale/2>=REQUIRED_SIZE && options.outHeight/scale/2>=REQUIRED_SIZE)
scale*=2;
//Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize=scale;
return BitmapFactory.decodeStream(input, null, o2);
} catch (IOException e) {
e.printStackTrace();
Log.e("Exception",e.getMessage());
return null;
}
}
Your InputStream is "eaten away". You can use a stream only once and hence when you read the bitmap headers in order to scale the image your input stream gets 'eaten away'. You need to create a new InputStream in order to get the real bitmap.
Related
I'm writing Espresso tests to run on my React Native app. I'm using Espresso-Intents to simulate the user taking a picture, with the following code:
public void takePicture() {
Instrumentation.ActivityResult result = createImageCaptureActivityResultStub();
intending(hasAction(MediaStore.ACTION_IMAGE_CAPTURE)).respondWith(result);
clickText("Camera");
}
public static Bitmap getBitmapFromURL(String src) {
try {
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (IOException e) {
// Log exception
System.out.println(e.toString());
return null;
}
}
private Instrumentation.ActivityResult createImageCaptureActivityResultStub() {
// Put the drawable in a bundle.
Bundle bundle = new Bundle();
bundle.putParcelable("data", getBitmapFromURL("https://vignette.wikia.nocookie.net/the-feed-your-pets-community/images/6/69/Banana.png/revision/latest?cb=20180527162222"));
// Create the Intent that will include the bundle.
Intent resultData = new Intent();
resultData.putExtras(bundle);
// Create the ActivityResult with the Intent.
return new Instrumentation.ActivityResult(Activity.RESULT_OK, resultData);
}
When running, the camera intent is successfully stubbed, but the view which should display the photo is stuck in its loading state.
In debugging, I have discovered that getBitmapFromURL is not the problem, because bundle contains the correct image.
Could anyone suggest where the problem may lie, or how best to debug further?
I want to load a lot of image like instagram do but still get OutOfMemory my code load 18 image at a time and can scroll down to load more.
I also cache image to disk and resize image to fit thumbnail before load to Bitmap
private Bitmap loadBitmap(String id) throws IOException{
String key = id.toLowerCase();
// Check disk cache in background thread
Bitmap image = cacher.get(key);
if (image == null){
// Not found in disk cache
// Process as normal
if(!isCancelled()){
//download image to stream
ByteArrayOutputStream stream = new ByteArrayOutputStream();
DriveApiActivity.getService().files().get(id)
.executeMediaAndDownloadTo(stream);
//decode image to byte array
byte[] byteArray = stream.toByteArray();
stream.close();
//decode byte array to bitmap file
image = decodeToBitmap(
byteArray,
CustomCardView.width,
CustomCardView.height);
// Add final bitmap to caches
cacher.put(key, image);
}
}
return image;
}
the Logcat say exception is come out of cacher.get() method
public Bitmap get(String key) {
synchronized (diskCacheLock) {
// Wait while disk cache is started from background thread
while (diskCacheStarting) {
try {
diskCacheLock.wait();
} catch (InterruptedException e) {
Toast.makeText(
context,
"getBitmapFromCache:" + e.getMessage(),
4).show();
}
}
if (diskLruCache != null) {
Bitmap bitmap = null;
DiskLruCache.Snapshot snapshot = null;
try{
snapshot = diskLruCache.get(key);
if(snapshot == null){
return null;
}
final InputStream in = snapshot.getInputStream(0);
if(in != null){
final BufferedInputStream buffIn =
new BufferedInputStream(in, Utils.IO_BUFFER_SIZE);
bitmap = BitmapFactory.decodeStream(buffIn);
}
}catch(IOException e){
e.printStackTrace();
}finally{
if(snapshot != null){
snapshot.close();
}
}
if(BuildConfig.DEBUG){
Log.d( "cache_test_DISK_", bitmap == null ? "" : "image read from disk " + key);
}
return bitmap;
}
}
return null;
}
this code come from DiskLruCache google provided
You have to use:
largeheap = true
in android. manifest file, from this line you cannot get out of memory error
It will solve your problem
Get pictures path from SDcard.
My picture name is 01.jpg.
Make sure the picture is inside the SD card.
public boolean fileIsExists(){
try{
File f1 = new File("/sdcard/01.jpg");
f1 = new File("01.jpg");
if(!f1.exists()){
return true;
}
}catch (Exception e) {
// TODO: handle exception
return false;
}
return true;
}
boolean file1 = fileIsExists();
If picture is inside the SD card,then put picture into imageview.
Error is in the following code
if (file1==true){
imageView = (ImageView)findViewById(R.id.image_view);
String myJpgPath = "/sdcard/01.jpg";
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 0;
Bitmap bitmap = BitmapFactory.decodeFile(myJpgPath, options);//error here Cellphone can't run
imageView.setImageBitmap(bitmap);
}
Just try Following Code.
File f = new File("/mnt/sdcard/01.jpg");
ImageView mImgView1 = (ImageView)findViewById(R.id.imageView);
Bitmap bmp = BitmapFactory.decodeFile(f.getAbsolutePath());
mImgView1.setImageBitmap(bmp);
set your path like this:
String myJpgPath = Environment.getExternalStorageDirectory().getAbsolutePath()+"folderName/01.jpg";
Change +"sdcard/01.jpg"; to +"/01.jpg";
(And make sure Bitmap bitmap isn't repeat the local variables.)
if (file1==true){
String myJpgPath = Environment.getExternalStorageDirectory().getAbsolutePath()+"/01.jpg";
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 0;
Bitmap bitmap = BitmapFactory.decodeFile(myJpgPath, options);
imageView.setImageBitmap(bitmap);
}
So I'm trying to restore an image from a file in my app's private files directory.
InputStream inputStream;
BitMapDrawable result;
try {
inputStream = new FileInputStream(file.getAbsolutePath());
result = BitmapDrawable.createFromStream(inputStream, null);
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
return result;
But obviously I'm doing something wrong because result is always null.
new BitmapDrawable( BitmapFactory.decodeFile(file.getAbsolutePath()) );
Isn't It what you want?
Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
Drawable d = new BitmapDrawable(getResources(),bitmap);
imageview.setImageDrawable(d);
I have been developing the application which need to set an image as wallpaper.
Code:
WallpaperManager m=WallpaperManager.getInstance(this);
String s=Environment.getExternalStorageDirectory().getAbsolutePath()+"/1.jpg";
File f=new File(s);
Log.e("exist", String.valueOf(f.exists()));
try {
InputStream is=new BufferedInputStream(new FileInputStream(s));
m.setBitmap(BitmapFactory.decodeFile(s));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("File", e.getMessage());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("IO", e.getMessage());
}
Also I have added the following permission:
<uses-permission android:name="android.permission.SET_WALLPAPER" />
But it doesn't works; the file exists on sdcard. Where have I made a mistake?
Possibly, you run out of memory if your image is big. You can make sure of it by reading Logcat logs. If this is the case, try to adjust your picture to device size by somewhat like this:
DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
int height = displayMetrics.heightPixels;
int width = displayMetrics.widthPixels << 1; // best wallpaper width is twice screen width
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, width, height);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
Bitmap decodedSampleBitmap = BitmapFactory.decodeFile(path, options);
WallpaperManager wm = WallpaperManager.getInstance(this);
try {
wm.setBitmap(decodedSampleBitmap);
} catch (IOException e) {
Log.e(TAG, "Cannot set image as wallpaper", e);
}
File f = new File(Environment.getExternalStorageDirectory(), "1.jpg");
String path = f.getAbsolutePath();
File f1 = new File(path);
if(f1.exists()) {
Bitmap bmp = BitmapFactory.decodeFile(path);
BitmapDrawable bitmapDrawable = new BitmapDrawable(bmp);
WallpaperManager m=WallpaperManager.getInstance(this);
try {
m.setBitmap(bmp);
} catch (IOException e) {
e.printStackTrace();
}
}
Open Androidmanifest.xml file and add permission like..
<uses-permission android:name="android.permission.SET_WALLPAPER" />
Try this and let me know what happen..