I understand that using BitmapFactory can convert a File to a Bitmap, but is there any way to convert a Bitmap image to a File?
Hope it will help u:
//create a file to write bitmap data
File f = new File(context.getCacheDir(), filename);
f.createNewFile();
//Convert bitmap to byte array
Bitmap bitmap = your bitmap;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 0 /*ignored for PNG*/, bos);
byte[] bitmapdata = bos.toByteArray();
//write the bytes in file
FileOutputStream fos = new FileOutputStream(f);
fos.write(bitmapdata);
fos.flush();
fos.close();
Try this:
bitmap.compress(Bitmap.CompressFormat.PNG, quality, outStream);
See this
File file = new File("path");
OutputStream os = new BufferedOutputStream(new FileOutputStream(file));
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os);
os.close();
Converting Bitmap to File needs to be done in background (NOT IN THE MAIN THREAD) it hangs the UI specially if the bitmap was large
File file;
public class fileFromBitmap extends AsyncTask<Void, Integer, String> {
Context context;
Bitmap bitmap;
String path_external = Environment.getExternalStorageDirectory() + File.separator + "temporary_file.jpg";
public fileFromBitmap(Bitmap bitmap, Context context) {
this.bitmap = bitmap;
this.context= context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
// before executing doInBackground
// update your UI
// exp; make progressbar visible
}
#Override
protected String doInBackground(Void... params) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
file = new File(Environment.getExternalStorageDirectory() + File.separator + "temporary_file.jpg");
try {
FileOutputStream fo = new FileOutputStream(file);
fo.write(bytes.toByteArray());
fo.flush();
fo.close();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
// back to main thread after finishing doInBackground
// update your UI or take action after
// exp; make progressbar gone
sendFile(file);
}
}
Calling it
new fileFromBitmap(my_bitmap, getApplicationContext()).execute();
you MUST use the file in onPostExecute .
To change directory of file to be stored in cache
replace line :
file = new File(Environment.getExternalStorageDirectory() + File.separator + "temporary_file.jpg");
with :
file = new File(context.getCacheDir(), "temporary_file.jpg");
Most of the answers are too lengthy or too short not fulfilling the purpose. For those how are looking for Java or Kotlin code to Convert bitmap to File Object. Here is the detailed article I have written on the topic. Convert Bitmap to File in Android
public static File bitmapToFile(Context context,Bitmap bitmap, String fileNameToSave) { // File name like "image.png"
//create a file to write bitmap data
File file = null;
try {
file = new File(Environment.getExternalStorageDirectory() + File.separator + fileNameToSave);
file.createNewFile();
//Convert bitmap to byte array
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 0 , bos); // YOU can also save it in JPEG
byte[] bitmapdata = bos.toByteArray();
//write the bytes in file
FileOutputStream fos = new FileOutputStream(file);
fos.write(bitmapdata);
fos.flush();
fos.close();
return file;
}catch (Exception e){
e.printStackTrace();
return file; // it will return null
}
}
Hope this helps u
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Get the bitmap from assets and display into image view
val bitmap = assetsToBitmap("tulip.jpg")
// If bitmap is not null
bitmap?.let {
image_view_bitmap.setImageBitmap(bitmap)
}
// Click listener for button widget
button.setOnClickListener{
if(bitmap!=null){
// Save the bitmap to a file and display it into image view
val uri = bitmapToFile(bitmap)
image_view_file.setImageURI(uri)
// Display the saved bitmap's uri in text view
text_view.text = uri.toString()
// Show a toast message
toast("Bitmap saved in a file.")
}else{
toast("bitmap not found.")
}
}
}
// Method to get a bitmap from assets
private fun assetsToBitmap(fileName:String):Bitmap?{
return try{
val stream = assets.open(fileName)
BitmapFactory.decodeStream(stream)
}catch (e:IOException){
e.printStackTrace()
null
}
}
// Method to save an bitmap to a file
private fun bitmapToFile(bitmap:Bitmap): Uri {
// Get the context wrapper
val wrapper = ContextWrapper(applicationContext)
// Initialize a new file instance to save bitmap object
var file = wrapper.getDir("Images",Context.MODE_PRIVATE)
file = File(file,"${UUID.randomUUID()}.jpg")
try{
// Compress the bitmap and save in jpg format
val stream:OutputStream = FileOutputStream(file)
bitmap.compress(Bitmap.CompressFormat.JPEG,100,stream)
stream.flush()
stream.close()
}catch (e:IOException){
e.printStackTrace()
}
// Return the saved bitmap uri
return Uri.parse(file.absolutePath)
}
}
Related
I have images in my drawables folder. Activity opens them, I choose the needed images and click on button. They must be saved on my SD Card through ImageSavingTask class instance execution which extends AsyncTask.
Here is my onClick code:
#Override
public void onClick(View v) {
for (int i = 0; i < 26; i++)
if (checkBoxes[i].isChecked()) {
imageIndex = new ImageIndex(); //ImageIndex-a class with single index field which reserves the checked checkbox indexes.
imageIndex.index = i;
Bitmap bitmap = ((BitmapDrawable) (images[i].getDrawable())).getBitmap();
SaveImageTask saveImageTask = new SaveImageTask();
saveImageTask.execute(bitmap); //The class SaveImageTask extends AsyncTask<Bitmap, Void, Void>
}
}
Then the selected images are handled in doInBackground method.
#Override
protected Void doInBackground(Bitmap... params) {
FileOutputStream outStream = null;
try {
Bitmap bitmap = params[0];
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] imageBytes = stream.toByteArray();
File sdCard = Environment.getExternalStorageDirectory();
Drawable drawable = new BitmapDrawable(getResources(), bitmap);
File dir = new File(sdCard.getAbsolutePath());
dir.mkdirs();
String fileName = "Saved image " + imageIndex.index; //The reserved index of checkbox creates a name for the new file.
File outFile = new File(dir, fileName);
outStream = new FileOutputStream(outFile);
outStream.write(imageBytes);
outStream.flush();
outStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
The <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> line is added in my manifest.
After I connect the USB to my phone, no error happens, but no images are saved to my SD Card. And I can't find images on my phone using windows search. Debugging doesn't give any answer. What kind of problem this could be?
It seems you have not asked runtime permissions for writing file on SD Card. From Android M and above you need to ask write permission at runtime to save any file on external sd card.
Check this link on how to request runtime permissions- https://developer.android.com/training/permissions/requesting.html
Also you can use google library - https://github.com/googlesamples/easypermissions
to request permissions.
I add the selected indexes into 2 ArrayLists of indexes and bitmaps. In the doInBackground method I created a loop.
For appearing the images on the card immediately I used the MediaScannerConnection.scanFile method.
for (int i = 0; i < 26; i++)
if (checkBoxes[i].isChecked()) {
index.add(i);
bitmap.add(bitmaps[i]);
}
if (bitmap.size() > 0)
new SaveImageTask().execute();
The doInBackground method:
protected Void doInBackground(Void... params) {
for (int i = 0; i < bitmap.size(); i++) {
try {
fname = "Saved image " + (index.get(i)) + ".jpg";
file = new File(myDir, fname);
if (file.exists()) file.delete();
FileOutputStream out = new FileOutputStream(file);
bitmap.get(i).compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
MediaScannerConnection.
scanFile(getApplicationContext(), new String[]{file.getPath()}, new String[]{"image/jpeg"}, null);
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
I left the ImageSavingTask without fields and parameters.
I think problem where you try to write bytes.
Use Following Solution..
#Override
protected Void doInBackground(Bitmap... params) {
Bitmap bitmap = params[0];
saveToInternalStorage(bitmap, "MyImage"); // pass bitmap and ImageName
return null;
}
//Method to save Image in InternalStorage
private void saveToInternalStorage(Bitmap bitmapImage, String imageName) {
File mypath = new File(Environment.getExternalStorageDirectory(), imageName + ".jpg");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(mypath);
// Use the compress method on the BitMap object to write image to the OutputStream
bitmapImage.compress(Bitmap.CompressFormat.JPEG, 100, fos);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
NOTE : Make sure you have added storage read/write permission and don't forget to ask permission on Marshmallow and higher version.
I know it's a very basic question but i am stuck to resolve this problem. I am working on image-sketching mobile app i have done all the work now I just want to store a resulting bitmap-image into internal memory.I have created a method "mageStore()" for image-storing purposes please write code there. I will be very thankful to you.
`private class ImageProcessingTask extends AsyncTask<Bitmap, Void, Bitmap> {
private ProgressDialog abhanDialog = null;
private Bitmap returnedBitmap = null;
#Override
protected void onPreExecute() {
returnedBitmap = null;
abhanDialog = new ProgressDialog(AbhanActivity.this);
abhanDialog.setMessage(getString(R.string.please_wait));
abhanDialog.setCancelable(false);
abhanDialog.show();
}
#Override
protected Bitmap doInBackground(Bitmap... params) {
final Bitmap sketched = AbhanSketch.createSketch(params[0]);
final Bitmap gaussianBitmap = AbhanEffects.applyGaussianBlur(sketched);
final Bitmap sepiaBitmap = AbhanEffects.sepiaTonnedBitmap(gaussianBitmap, 151, 0.71,
0.71, 0.76);
returnedBitmap = AbhanEffects.sharpenBitmap(sepiaBitmap, 0.81);
return returnedBitmap;
}
#Override
protected void onPostExecute(Bitmap result) {
if (abhanDialog != null && abhanDialog.isShowing()) {
abhanDialog.cancel();
}
if (result != null) {
mImageView.setImageBitmap(result);
mImageView.buildDrawingCache();
bmap = mImageView.getDrawingCache();
storeImage(bmap);
isImage = false;
enableButton();
final boolean isFileDeleted = Utils.deleteFile(mPath);
if (DEBUG) {
android.util.Log.i(TAG, "File Deleted: " + isFileDeleted);
}
}
}
}
private void storeImage(Bitmap image) {
...please enter code here for image storing
}`
Here is your missing code inside a function
private void storeImage(Bitmap image) {
File sdcard = Environment.getExternalStorageDirectory() ;
File folder = new File(sdcard.getAbsoluteFile(), "YOUR_APP_DIRECTORY");
if(!folder.exists())
folder.mkdir();
File file = new File(folder.getAbsoluteFile(), "IMG_" + System.currentTimeMillis() + ".jpg") ;
if (file.exists())
file.delete();
try {
FileOutputStream out = new FileOutputStream(file);
bitmap = Bitmap.createScaledBitmap(bitmap, 400, (int) ( bitmap.getHeight() * (400.0 / bitmap.getWidth()) ) ,false);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
You can omit or edit this line
bitmap = Bitmap.createScaledBitmap(bitmap, 400, (int) ( bitmap.getHeight() * (400.0 / bitmap.getWidth()) ) ,false);
according to your need.
in your function write the following code
String path = Saveme(image,"image_name.jpg");
//path contains the full path to directory where all your images get stored internaly lolz but privately
for gallery
Saveme(image,"my image","my image test for gallery save");
and the defination for the Saveme() function is following
private String Saveme(Bitmap bitmapImage, String img_name){
ContextWrapper cw = new ContextWrapper(getApplicationContext());
// path to /data/data/yourapp/app_data/imageDir
File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
// Create imageDir
File mypath=new File(directory,img_name);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(mypath);
// Use the compress method on the BitMap object to write image to the OutputStream
bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fos);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return directory.getAbsolutePath();
}
in gallery images are displayed from media store so you need to store image in media store the following code can help you for this
public void Saveme(Bitmap b, String title, String dsc)
{
MediaStore.Images.Media.insertImage(getContentResolver(), b, title ,dsc);
}
I want to save a created bitmap after a button clicked
How can I do that? and if possible to a specific location
Here are my codes:
quoteimage.requestLayout();
if (quoteimage.getViewTreeObserver().isAlive()) {
quoteimage.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
// we check which build version we are using
#SuppressLint("NewApi")
#SuppressWarnings("deprecation")
#Override
public void onGlobalLayout() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
quoteimage.getViewTreeObserver().removeGlobalOnLayoutListener(this);
} else {
quoteimage.getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
viewToBitmap(quoteimage); ///this one creates the bitmap
}
});
}
share.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
///Here I want to save the bitmap
}
});
Call save() in onClick():
protected void save(){
FileOutputStream out = null;
try {
out = new FileOutputStream(filename);
bmp.compress(Bitmap.CompressFormat.PNG, 100, out); // bmp is your Bitmap instance
// PNG is a lossless format, the compression factor (100) is ignored
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}}
Use this method to save your bitmap, also pass the file name and location as U like
private createDirectoryAndSaveFile(Bitmap imageToSave, String fileName,String location) {
File direct = new File(Environment.getExternalStorageDirectory() + "/"+location);
if (!direct.exists()) {
File wallpaperDirectory = new File("/sdcard/"+location+"/");
wallpaperDirectory.mkdirs();
}
File file = new File(new File("/sdcard/"+location+"/"), fileName+".jpg");
if (file.exists()) {
file.delete();
}
try {
FileOutputStream out = new FileOutputStream(file);
imageToSave.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
File externalFile = new File(Environment.getExternalStorageDirectory(),"your/location/"+fileName+".jpg");
externaluri = Uri.parse(externalFile.getPath());
Log.d("externaluri", externaluri.toString());
}
Example
createDirectoryAndSaveFile(yourbitmap, "your_image_name" ,"your/location");
Android Saving created bitmap to directory on sd card
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
_bitmapScaled.compress(Bitmap.CompressFormat.JPEG, 40, bytes);
//you can create a new file name "test.jpg" in sdcard folder.
File f = new File(Environment.getExternalStorageDirectory()
+ File.separator + "test.jpg")
f.createNewFile();
//write the bytes in file
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
// remember close de FileOutput
fo.close();
Having trouble with File coding. This code basically save the bitmap file into android gallery.
Java.IO.File MyDirectory = new Java.IO.File(Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryPictures), "MyDirectory");
Java.IO.File MyFile= new Java.IO.File(MyDirectory , String.Format("Photo{0}.jpg", Guid.NewGuid()));
Bitmap photo;
Bundle extras = data.Extras;
photo = (Bitmap)extras.Get("data")
How to save the photo (Bitmap) into MyFolder android gallery?
I have tried this to save the photo:
Java.IO.FileOutputStream outFile = new Java.IO.FileOutputStream(MyFile);
photo.Compress(Bitmap.CompressFormat.Png, 100, outFile);
Error I received is when the photo is compress..
error: Cannot convert from Java.IO.FileOutputStream to System.IO.Stream.
Sorry, I am very newbie in File coding. Any helps or solutions are appreciated.
Here is my code.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
public static void saveBitmap(Context context, Bitmap bitmap) {
String env = Environment.getExternalStorageDirectory().getPath();
String path = env + "/test.png";
try {
File f = new File(path);
FileOutputStream fileOut = new FileOutputStream(f);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fileOut);
try {
fileOut.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
bitmap.recycle();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
This should work
var file = new FileStream(fname, FileMode.Create, FileAccess.Write, FileShare.None);
photo.Compress(Bitmap.CompressFormat.Jpeg, 85, file);
I use alternative way to compress my bitmap (using MemoryStream) and here is my code.
using(Bitmap bitmap = BitmapFactory.DecodeFile(myFileString))
{
MemoryStream stream = new MemoryStream();
bitmap.Compress(Bitmap.CompressFormat.Jpeg, 100, stream);
myWebService.functionSave(stream.ToArray());
}
//myWebservice function parameter.
functionSave(byte[] fileStream)
{
//... save your bitmap code using byte[]
}
Here is my code when I am writing to the file
Bitmap bitmap;
InputStream is;
try
{
is = (InputStream) new URL(myUrl).getContent();
bitmap = BitmapFactory.decodeStream(is);
is.close();
//program crashing here
File f = File.createTempFile(myUrl,null,MyApplication.getAppContext().getCacheDir());
FileOutputStream fos = new FileOutputStream(f);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
}
catch(Exception e)
{
bitmap = null;
}
And here is my code reading from the same file
Bitmap bitmap;
try
{
File f = new File(myUrl);
FileInputStream fis = new FileInputStream(f);
BufferedInputStream bis = new BufferedInputStream(fis);
byte[] bitmapArr = new byte[bis.available()];
bis.read(bitmapArr);
bitmap = BitmapFactory.decodeByteArray(bitmapArr, 0, bitmapArr.length);
bis.close();
fis.close();
}
catch(Exception e)
{
bitmap = null;
}
The program is crashing at the creation of the temp file in the first chunk of code.
EDIT: I am getting a libcore.io.ErrnoException
UPDATE: I found the problem and fixed it, for anyone interested see below.
I changed it to use the openFileOutput(String, int), and openFileInput(String) methods, I should have done it this way right from the beginning.
The following is working code to decode an input stream from a url containing an image into a bitmap, compress the bitmap and store it into a file, and to retrieve said bitmap from that file later.
Bitmap bitmap;
InputStream is;
try
{
is = (InputStream) new URL(myUrl).getContent();
bitmap = BitmapFactory.decodeStream(is);
is.close();
String filename = "file"
FileOutputStream fos = this.openFileOutput(filename, Context.MODE_PRIVATE);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.close();
}
catch(Exception e)
{
bitmap = null;
}
and
Bitmap bitmap;
try
{
String filename = "file";
FileInputStream fis = this.openFileInput(filename);
bitmap = BitmapFactory.decodeStream(fis);
fis.close();
}
catch(Exception e)
{
bitmap = null;
}