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);
Related
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.
In a React Native app for Android, I am trying to write an image (passed as base64) onto the filesystem and later decode it using BitmapFactory.
Why is BitmapFactory still unable to decode the image after using (Base64.decode) while storing it?
The error:
Cannot decode bitmap:
file:///data/data/com.reactnativeapp/files/rct-image-store/1
The custom written method storing the image:
#ReactMethod
public void addImageFromBase64(String base64_image_data, Callback successCallback, Callback failureCallback){
String imageStorageDir = this.reactContext.getApplicationContext().getFilesDir()+"/rct-image-store/";
String file_uri = imageStorageDir+"1";
try {
File f = new File(imageStorageDir);
if(!f.exists()) {
f.mkdir();
}
FileOutputStream fos = new FileOutputStream(file_uri, false);
byte[] decodedImage = Base64.decode(base64_image_data, Base64.DEFAULT);
fos.write(decodedImage);
fos.close();
successCallback.invoke("file://"+file_uri);
} catch (IOException ioe) {
failureCallback.invoke("Failed to add image from base64String"+ioe.getMessage());
} catch (Exception e) {
failureCallback.invoke("Failed to add image from base64String"+e.getMessage());
}
}
Shortened method for accessing the image (fullResolutionBitmap is null):
InputStream inputStream = mContext.getContentResolver().openInputStream(Uri.parse(uri));;
BitmapFactory.Options outOptions = new BitmapFactory.Options();
Bitmap fullResolutionBitmap = BitmapFactory.decodeStream(inputStream, null, outOptions);/// fullResolutionBitmap==null
Here is the image, the bottom part looks cropped. Since both original and converted image have the grey area, the problem seems to be not with the conversion of the image, but with the source (camera).
Original image:
Converted image:
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.
I am trying to use the VuDroid PDF viewer and I need to take the rendered bitmap and store it as a byte[]. Then I need to convert it back into a Bitmap that can be displayed on a view using something like "canvas.drawBitmap(bitmap, 0, 0, paint);".
I have spent many hours trying to access the Bitmap and I might have done it already, but even if I get the byte[] to return something it still wont render as a Bitmap on the canvas.
Could someone please help me here, I must be missing something. Thank you so much.
I believe it is supposed to accessed via...
PDFPage.java .... public Bitmap renderBitmap(int width, int height, RectF pageSliceBounds)
-or-
through Page.java -or- DocumentView.java -or- DecodeService.java
Like I said I have tried all of these and have gotten results I just cannot see where I am going wrong since I cannot render it to see if the Bitmap was called correctly.
Thank you again :)
The doc says the method returns "null if the image could not be decode." You can try:
byte[] image = services.getImageBuffer(1024, 600);
InputStream is = new ByteArrayInputStream(image);
Bitmap bmp = BitmapFactory.decodeStream(is);
I think This will help you:-
Render a byte[] as Bitmap in Android
How does Bitmap.Save(Stream, ImageFormat) format the data?
Copy image with alpha channel to clipboard with custom background color?
if you want to get each pdf page as independent bitmap you should consider that
VuDroid render the pages,
PDFView only display them.
you should use VuDroid functions.
now you can use this example and create your own codes
Example code : for make bitmap from a specific PDF page
view = (ImageView)findViewById(R.id.imageView1);
pdf_conext = new PdfContext();
PdfDocument d = pdf_conext.openDocument(Environment.getExternalStorageDirectory() + "your PDF path");
PdfPage vuPage = d.getPage(1); // choose your page number
RectF rf = new RectF();
rf.bottom = rf.right = (float)1.0;
Bitmap bitmap = vuPage.renderBitmap(60, 60, rf); //define width and height of bitmap
view.setImageBitmap(bitmap);
for writing this bitmap on SDCARD :
try {
File mediaImage = new File(Environment.getExternalStorageDirectory().toString() + "your path for save thumbnail images ");
FileOutputStream out = new FileOutputStream(mediaImage);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
for retrieve saved image:
File file = new File(Environment.getExternalStorageDirectory().toString()+ "your path for save thumbnail images ");
String path = file.getAbsolutePath();
if (path != null){
view = Bitmap.createScaledBitmap(BitmapFactory.decodeFile(path), YOUR_X, YOUR_Y, false);
}
Try this code to check whether bitmap is properly generating or not
PdfContext pdf_conext = new PdfContext();
PdfDocument d = (PdfDocument) pdf_conext.openDocument(pdfPath);
PdfPage vuPage = (PdfPage) d.getPage(0);
RectF rf = new RectF();
Bitmap bitmap = vuPage.renderBitmap(1000,600, rf);
File dir1 = new File (root.getAbsolutePath() + "/IMAGES");
dir1.mkdirs();
String fname = "Image-"+ 2 +".jpg";
File file = new File (dir1, fname);
if (file.exists ())
file.delete ();
try {
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
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.