Android set background from filepath - android

I would like to do something similar to imageView.setImageResource(R.drawable.myimage); but instead of providing an image from my app's resources, I would like to point to a file (/sdcard/.../image.jpg).
Is there a way to do that that does not involve loading the Bitmap and then setting the bitmap to the imageview ?
Thanks

You can update background from SDCard as follows...
String pathName = Environment.getExternalStorageDirectory().getPath() + "/folder/" + "image.jpg";
Bitmap bitmap = BitmapFactory.decodeFile(pathName);
imageView.setImageBitmap(bitmap);

Try this way
public Bitmap ImgBitFromFile(String file_name) {
File imgFile = new File(file_name);
if (imgFile.exists()) {
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
return myBitmap;
}
return null;
}
And used like:
img.setImageBitmap(ImgBitFromFile(File_Path));
And do not Forget to add READ Permission in your manifest.xml file.

Related

Get and display image in android from inputstream

Starting off by saying I'm new to the Android language and I need help with something.
I'm trying to get an image from an inputstream connected to my java program and save it to the internal storage and after that I display it. However I'm not recieving any errors at all from my code and yet the image is not displaying at all. There is no problem with my Java program/file since it works 100% with another program I wrote in Java which does the same thing Im trying to do with my Android Application.
public void GetImage()
{
try
{
InputStream inputStream = new BufferedInputStream(connectionSocket.getInputStream());
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
FileOutputStream out = new FileOutputStream(getFilesDir() + "james.png");
bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
}
catch (IOException e)
{
Log.d("ERROR", "GetImage: " + e);
}
}
public void DisplayImage()
{
ImageView myImageview = (ImageView) findViewById(R.id.myImageView);
int imageResource = getResources().getIdentifier(getFilesDir() + "james.png", null, this.getPackageName());
myImageview.setImageResource(imageResource);
}
Can anyone take a look at the code and tell me what I'm doing wrong? Thank you
File imgFile = new File(getFilesDir() + "james.png");
if(imgFile.exists()){
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
ImageView myImageview = (ImageView) findViewById(R.id.myImageView);
myImageview.setImageBitmap(myBitmap);
}
Please replace your method code with it

Android BitmapFactory.decodeFile on jpeg file returns null

My app calls the camera to take a picture and save it into my app local directory (getApplicationContext().getFilesDir()) which works fine.
When I try to convert the picture into a bitmap using BitmapFactory the result is null. This the code I use :
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 8;
String picturePath = pictureFile.getAbsolutePath();
Bitmap bitmap = BitmapFactory.decodeFile(picturePath, options);
Note that pictureFile was created as follows :
pictureFile = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
foodwarnDir /* directory */
);
Didn't you forget add permissions READ_EXTERNAL_STORAGE and/or WRITE_EXTERNAL_STORAGE ?
File locationOfFile = new
File(Environment.getExternalStorageDirectory().getAbsolutePath()+ "/images");
File destination= new File(locationOfFile , fileName + ".JPG");
FileInputStream fileInputStream;
fileInputStream= new FileInputStream(destination);
Bitmap img = BitmapFactory.decodeStream(fileInputStream);
OR
This is my working code in my project here:
View imageHolder = LayoutInflater.from(this).inflate(R.layout.image_item, null);
ImageView thumbnail = (ImageView) imageHolder.findViewById(R.id.media_image);
try {
String path = uri.getPath();
Bitmap bmImg = BitmapFactory.decodeFile(path);
Point p = new Point();
p.set(100, 100);
Bitmap bitmapp = waterMark(bmImg, mRefNo, p, Color.RED, 90, 60, true);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmapp.compress(Bitmap.CompressFormat.PNG, 100, stream);
Glide.with(this)
.load(stream.toByteArray())
.asBitmap()
.error(R.mipmap.ic_launcher)
.into(thumbnail);
mSelectedImagesContainer.addView(imageHolder);
thumbnail.setLayoutParams(new FrameLayout.LayoutParams(wdpx, htpx));
} catch (Exception e) {
e.printStackTrace();
}
Hope this helps you
other helpful Links1 Link2
Create temp file:
File tempFile = File.createTempFile("temp_file, ".jpg", this.getExternalCacheDir());
get path created:
String mPath = tempFile.getAbsolutePath();
now in you activityResult
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
options.inSampleSize = 8;
Bitmap bitmap = BitmapFactory.decodeFile(mPath, options);
use
data.getExtras().get("data");//for getting bitmap
Uri u = intent.getData();// for getting the Uri and get the path from uri
for getting data from your camera
Assuming you're using java.io.File class. According to Java docs function .createTempFile creates empty file on the System.
As such, this file will have only meta info without any content, with zero length, and this is probably a reason why it is not possible to extract Bitmap.
So you need to Create File Object instance instead of actual file, using new File()
You can also use WeakReference and similar to Bitmap you create if you're looking to decrease chance of memory leaks in early implementation.

Displaying image from sd card

I use this code
String imgFile = Environment.getExternalStorageDirectory() + "/p1.png";
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile);
image.setImageBitmap(myBitmap);
but imageview's background isn't p1.png there is no image at the background it is white please help.Thanks..
You should use the full path of the SDCard. Then you can do normal I/O-Operations just like this:
String imgFile = String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "p1.png";
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile);
image.setImageBitmap(myBitmap);r code here

How can I write a Drawable resource to a File?

I need to export some Drawable resources to a file.
For example, I have a function that returns to me a Drawable object. I want to write it out to a file in /sdcard/drawable/newfile.png. How can i do it?
Although the best answer here have a nice approach. It's link only. Here's how you can do the steps:
Convert Drawable to Bitmap
You can do that in at least two different ways, depending on where you're getting the Drawable from.
Drawable is on res/drawable folders.
Say you want to use a Drawable that is on your drawable folders. You can use the BitmapFactory#decodeResource approach. Example below.
Bitmap bm = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.your_drawable);
You have a PictureDrawable object.
If you're getting a PictureDrawable from somewhere else "at runtime", you can use the Bitmap#createBitmap approach to create your Bitmap. Like the example below.
public Bitmap drawableToBitmap(PictureDrawable pd) {
Bitmap bm = Bitmap.createBitmap(pd.getIntrinsicWidth(), pd.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bm);
canvas.drawPicture(pd.getPicture());
return bm;
}
Save the Bitmap to disk
Once you have your Bitmap object, you can save it to the permanent storage. You'll just have to choose the file format (JPEG, PNG or WEBP).
/**
* #param dir you can get from many places like Environment.getExternalStorageDirectory() or mContext.getFilesDir() depending on where you want to save the image.
* #param fileName The file name.
* #param bm The Bitmap you want to save.
* #param format Bitmap.CompressFormat can be PNG,JPEG or WEBP.
* #param quality quality goes from 1 to 100. (Percentage).
* #return true if the Bitmap was saved successfully, false otherwise.
*/
boolean saveBitmapToFile(File dir, String fileName, Bitmap bm,
Bitmap.CompressFormat format, int quality) {
File imageFile = new File(dir,fileName);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(imageFile);
bm.compress(format,quality,fos);
fos.close();
return true;
}
catch (IOException e) {
Log.e("app",e.getMessage());
if (fos != null) {
try {
fos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
return false;
}
And to get the target directory, try something like:
File dir = new File(Environment.getExternalStorageDirectory() + File.separator + "drawable");
boolean doSave = true;
if (!dir.exists()) {
doSave = dir.mkdirs();
}
if (doSave) {
saveBitmapToFile(dir,"theNameYouWant.png",bm,Bitmap.CompressFormat.PNG,100);
}
else {
Log.e("app","Couldn't create target directory.");
}
Obs: Remember to do this kind of work on a background Thread if you're dealing with large images, or many images, because it can take some time to finish and might block your UI, making your app unresponsive.
get the image stored in sdcard..
File imgFile = new File(“/sdcard/Images/test_image.jpg”);
if(imgFile.exists()){
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
ImageView myImage = (ImageView) findViewById(R.id.imageviewTest);
myImage.setImageBitmap(myBitmap);
}
Update:
String path = Environment.getExternalStorageDirectory()+ "/Images/test.jpg";
File imgFile = new File(path);

Download and show the Thumbnail

I try to download a picture from URL to SD card/Download.
And I try to show its thumbnail in imageview.
Now I had below code:
try {
Download(URL); //download picture to SD card/Download
File myfile = new File(Environment.getExternalStorageDirectory() + "/Download/", filename);
Drawable photo = null;
photo = Drawable.createFromPath(myfile.getPath());
imageview.setBackgroundDrawable(photo);
}
It show the original picture.
But when the picture is large.
The memory error occurs.
So I want to show the smaller picture.
How should I do to generate the thumbnail and show it?
Or how to use the thumbnail generate by Android system?
Use Bitmap, Something like,
try
{
Download(URL); //download picture to SD card/Download
final int THUMBNAIL_SIZE = 64;
FileInputStream fis = new FileInputStream(Environment.getExternalStorageDirectory() + "/Download/", filename);
Bitmap imageBitmap = BitmapFactory.decodeStream(fis);
imageBitmap = Bitmap.createScaledBitmap(imageBitmap, THUMBNAIL_SIZE, THUMBNAIL_SIZE, false);
imageview.setImageBitmap(imageBitmap);
}
catch(Exception ex) {
}
From the Shown Code
Try this instead your last 2 lines
Bitmap photo = Bitmap.createScaledBitmap(BitmapFactory.decodeFile(myfile.getPath()),60,60,true);
imageview.setImageBitmap(photo);
And if you have made any objects for Bitmap/String/Stream in your Download() function free them calling System.gc();
And I hope this will work.

Categories

Resources