I'm having problems implementing this code Saving and Reading Bitmaps/Images from Internal memory in Android
to save and retrieve the image that I want, here is my code:
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, + name + "profile.jpg");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(mypath);
// Use the compress method on the BitMap object to write image to the OutputStream
myBitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
and to retrieve(I don't know if I'm doing wrong)
#Override
protected void onResume()
{
super.onResume();
try {
File f = new File("imageDir/" + rowID, "profile.jpg");
Bitmap b = BitmapFactory.decodeStream(new FileInputStream(f));
image = (ImageView) findViewById(R.id.imageView2);
image.setImageBitmap(b);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
and nothing happens so what should I change??
To Save your bitmap in sdcard use the following code
Store Image
private void storeImage(Bitmap image) {
File pictureFile = getOutputMediaFile();
if (pictureFile == null) {
Log.d(TAG,
"Error creating media file, check storage permissions: ");// e.getMessage());
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
image.compress(Bitmap.CompressFormat.PNG, 90, fos);
fos.close();
} catch (FileNotFoundException e) {
Log.d(TAG, "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d(TAG, "Error accessing file: " + e.getMessage());
}
}
To Get the Path for Image Storage
/** Create a File for saving an image or video */
private File getOutputMediaFile(){
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(Environment.getExternalStorageDirectory()
+ "/Android/data/"
+ getApplicationContext().getPackageName()
+ "/Files");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmm").format(new Date());
File mediaFile;
String mImageName="MI_"+ timeStamp +".jpg";
mediaFile = new File(mediaStorageDir.getPath() + File.separator + mImageName);
return mediaFile;
}
I think Faibo's answer should be accepted, as the code example is correct, well written and should solve your specific problem, without a hitch.
In case his solution doesn't meet your needs, I want to suggest an alternative approach.
It's very simple to store image data as a blob in a SQLite DB and retrieve as a byte array. Encoding and decoding takes just a few lines of code (for each), works like a charm and is surprisingly efficient.
I'll provide a code example upon request.
Good luck!
Note that you are saving the pick as name + profile.jpg under imageDir directory and you're trying to retrieve as profile.jpg under imageDir/[rowID] directory check that.
I got it working!
First make sure that your app has the storage permission enabled:
Go to Device Settings>Device>Applications>Application Manager>"your app">Permissions>Enable Storage permission!
Permissions in manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
So, if you want to create your own directory in your File Storage you can use somethibng like:
FileOutputStream outStream = null;
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File(sdCard.getAbsolutePath() + "/camtest");
dir.mkdirs();
String fileName = String.format("%d.jpg", System.currentTimeMillis());
File outFile = new File(dir, fileName);
outStream = new FileOutputStream(outFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
outStream.flush();
outStream.close();
refreshGallery(outFile);
Else, if you want to create a sub directory in your default device DCIM folder and then want to view your image in a separate folder in gallery:
FileOutputStream fos= null;
File file = getDisc();
if(!file.exists() && !file.mkdirs()) {
//Toast.makeText(this, "Can't create directory to store image", Toast.LENGTH_LONG).show();
//return;
print("file not created");
return;
}
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyymmsshhmmss");
String date = simpleDateFormat.format(new Date());
String name = "FileName"+date+".jpg";
String file_name = file.getAbsolutePath()+"/"+name;
File new_file = new File(file_name);
print("new_file created");
try {
fos= new FileOutputStream(new_file);
Bitmap bitmap = viewToBitmap(iv, iv.getWidth(), iv.getHeight() );
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
Toast.makeText(this, "Save success", Toast.LENGTH_LONG).show();
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
print("FNF");
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
refreshGallery(new_file);
Helper functions:
public void refreshGallery(File file){
Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
intent.setData(Uri.fromFile(file));
sendBroadcast(intent);
}
private File getDisc(){
String t= getCurrentDateAndTime();
File file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
return new File(file, "ImageDemo");
}
private String getCurrentDateAndTime() {
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
String formattedDate = df.format(c.getTime());
return formattedDate;
public static Bitmap viewToBitmap(View view, int width, int height) {
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
view.draw(canvas);
return bitmap;
}
Hope this helps!
Related
I want to save image to Pictures folder in android. I do not have any external memory card attached.
Code:
String ImageDirectory = "QrCode";
#RequiresApi(api = Build.VERSION_CODES.N)
public void saveImage(Bitmap myBitmap, String busNumber, String imageName, EditText imagePath) {
String IMAGE_DIRECTORY = "QRCode";
try (ByteArrayOutputStream bytes = new ByteArrayOutputStream()) {
myBitmap.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
File wallpaperDirectory = new File( Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),IMAGE_DIRECTORY+ "/" + busNumber );
// have the object build the directory structure, if needed.
if (!wallpaperDirectory.exists()) {
Log.d("dirrrrrr", "" + wallpaperDirectory.mkdirs());
wallpaperDirectory.mkdirs();
}
try {
File f = new File(wallpaperDirectory, imageName + ".jpeg");
imagePath.setText("Sandeep");
f.createNewFile(); //give read write permission
imagePath.setText("Chintu");
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
MediaScannerConnection.scanFile(this,
new String[]{f.getPath()},
new String[]{"image/jpeg"}, null);
imagePath.setText("f.getAbsolutePath()");
fo.close();
Log.d("TAG", "File Saved::--->" + f.getAbsolutePath());
Toast.makeText(getBaseContext(), f.getAbsolutePath(), Toast.LENGTH_SHORT).show();
//return f.getAbsolutePath();
} catch (IOException e1) {
e1.printStackTrace();
//imagePath.setText("Pintu");
}
} catch (IOException e) {
e.printStackTrace();
}
}
imagePath.setText("Sandeep"); is executed. But imagePath.setText("Chintu"); is not executed. So, it throws exception at f.createNewFile(); catch block is executed and imagePath.setText("Pintu"); is executed
manifestfile:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
You are using wroing picture directory. The path of Picture directory:
File pictureDir= Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File file = new File(pictureDir, "ImageName.jpg");
Here, I am generating Qr code as an image view. I want to save that image file into phone gallery. Please, help me.
first of all create bitmap from imageview using following code
BitmapDrawable drawable = (BitmapDrawable) imageView.getDrawable();
Bitmap bitmap = drawable.getBitmap();
now save this bitmap in internal storage
private void storeImage(Bitmap image) {
File pictureFile = getOutputMediaFile();
if (pictureFile == null) {
Log.d(TAG,
"Error creating media file, check storage permissions: ");// e.getMessage());
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
image.compress(Bitmap.CompressFormat.PNG, 90, fos);
fos.close();
} catch (FileNotFoundException e) {
Log.d(TAG, "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d(TAG, "Error accessing file: " + e.getMessage());
}
}
/** Create a File for saving an image or video */
private File getOutputMediaFile(){
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new
File(Environment.getExternalStorageDirectory()
+ "/Android/data/"
+ getApplicationContext().getPackageName()
+ "/Files");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmm").format(new Date());
File mediaFile;
String mImageName="MI_"+ timeStamp +".jpg";
mediaFile = new File(mediaStorageDir.getPath() + File.separator + mImageName);
return mediaFile;
}
I am working on app that store its image from resource to gallery. with the below code, it does not give an error but do not work. help me through this.
RelativeLayout fulllayout;
File root = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "/ZXMCO Images");
fulllayout = (RelativeLayout) findViewById(R.id.layout);
public void save()
{
fulllayout.setDrawingCacheEnabled(true);
fulllayout.buildDrawingCache();
Bitmap localBitmap = fulllayout.getDrawingCache();
saveToInternalStorage(localBitmap);
}
private void saveToInternalStorage(Bitmap bitmapImage){
File pictureFile = getOutputMediaFile();
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
bitmapImage.compress(Bitmap.CompressFormat.PNG, 90, fos);
fos.close();
} catch (FileNotFoundException e) {
Log.d(TAG,"File not found: " + e.getMessage());
} catch (IOException e) {
Log.d(TAG, "Error accessing file: " + e.getMessage());
}
}
private File getOutputMediaFile() {
if (! root.exists()){
root.mkdirs();
}
String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmm").format(new Date());
File mediaFile;
String mImageName="MI_"+ timeStamp +".jpg";
mediaFile = new File(root.getPath() + File.separator + mImageName);
return mediaFile;
}
It just show nothing. run without an error but could not find the image in gallery.
I Think the problem here is the Gallery didn't know that theres new images is stored on the device so we will need to notify it
There's two way to do that
Pre - Kitkat
using Boradcast
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory())));
Kitkat
You Can user the MediaScannerConnection to scan the new files
MediaScannerConnection.scanFile(context, new String[]{imageURL}, null,implment Listener Here);
I am capturing the image using camera in my android app.
then Cropping the image.
after Cropping saving the image in specified folder.
Folder is creating, But image is not saving in the folder.(Its Empty)
Help me to resolve it
code I have used,
link referred
if (extras != null) {
Bitmap photooutput = extras.getParcelable("data");
// Camera Output
if (pick == 1) {
viewImage.setImageBitmap(photooutput);
String path = Environment.getExternalStorageDirectory().toString();
File m_imgDirectory = new File(path + "/WallPaper/");
if (!m_imgDirectory.exists()) m_imgDirectory.mkdir();
FileOutputStream m_fOut = null;
File directory2 = new File(path);
directory2.delete();
String m_fileid = System.currentTimeMillis() + "";
directory2 = new File(path, "/Wall/" + m_fileid + ".png");
try
{
if (!directory2.exists()) directory2.createNewFile();
m_fOut = new FileOutputStream(directory2);
Bitmap m_bitmap = photooutput.copy(Bitmap.Config.ARGB_8888, true);
m_bitmap.compress(Bitmap.CompressFormat.PNG, 100, m_fOut);
m_fOut.flush();
m_fOut.close();
MediaStore.Images.Media.insertImage(getContentResolver(),
directory2.getAbsolutePath(), directory2.getName(), directory2.getName());
}
catch (Exception p_e)
{
}
}
}
When using Android KitKat and above, it is impossible for an app to save a file onto the SDCard.
Check this Thread
UPDATE
Save an image to internal storage:
public static Uri saveImage(Bitmap bmp) {
Uri uri = null;
try {
String name = System.currentTimeMillis() + ".jpg";
//you can create a new file name "test.jpg" in sdcard folder.
File f = new File(getImagesDir() + File.separator + name);
f.createNewFile();
//write the bytes in file
FileOutputStream fo = new FileOutputStream(f);
fo.write(bitmapToByteArray(bmp));
// remember close de FileOutput
fo.close();
uri = Uri.parse("file://" + f.getPath());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return uri;
}
public static String getImagesDir() {
String rootDir = Environment.getExternalStorageDirectory().toString();
rootDir = rootDir + "/MyApp/Media/Images";
// Create directory if not existed
File dir = new File(rootDir);
if (!dir.exists()) {
dir.mkdir();
}
return dir.getPath();
}
public static byte[] bitmapToByteArray(Bitmap bmp) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
return byteArray;
}
UPDATE 2: missing code added
Add the following permissions to your AndroidManifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
I have a Bitmap image which I have to store in a folder in the SD Card, my code is shown below. It creates the folder and file as expected, but the image is not stored into the file, it remains an empty file... Can anyone tell me what's wrong?
Bitmap merged = Bitmap.createBitmap(mDragLayer.getChildAt(0).getWidth(), mDragLayer.getChildAt(0).getHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(merged);
// save to folder in sd card
try {
File imagesFolder = new File(Environment.getExternalStorageDirectory(), "folder");
if(!imagesFolder.exists())
imagesFolder.mkdirs();
int imageNum;
if(imagesFolder.list()==null)
imageNum = 1;
else
imageNum = imagesFolder.list().length + 1;
String fileName = "file_" + String.valueOf(imageNum) + ".jpg";
File output = new File(imagesFolder, fileName);
while(output.exists()){
imageNum++;
fileName = "file_" + String.valueOf(imageNum) + ".jpg";
output = new File(imagesFolder, fileName);
}
OutputStream fOut = new FileOutputStream(output);
merged.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
fOut.flush();
fOut.close();
Toast.makeText(getApplicationContext(), "Saved", Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
First add permission to AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
Then write down in Java File as below.
String extr = Environment.getExternalStorageDirectory().toString();
File mFolder = new File(extr + "/MyApp");
if (!mFolder.exists()) {
mFolder.mkdir();
}
String strF = mFolder.getAbsolutePath();
File mSubFolder = new File(strF + "/MyApp-SubFolder");
if (!mSubFolder.exists()) {
mSubFolder.mkdir();
}
String s = "myfile.png";
f = new File(mSubFolder.getAbsolutePath(),s);
UPDATED
String strMyImagePath = f.getAbsolutePath();
FileOutputStream fos = null;
try {
fos = new FileOutputStream(f);
bitmap.compress(Bitmap.CompressFormat.PNG,70, fos);
fos.flush();
fos.close();
// MediaStore.Images.Media.insertImage(getContentResolver(), b, "Screen", "screen");
}catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
Don't make it difficult with complex code its really very simple please Try below code.
Create first dir in your sd card :
public static String strpath = android.os.Environment.getExternalStorageDirectory().toString();
public static String dirName = "DIR_NAME";
File makeDirectory = new File(strpath+"/"+dirName);
makeDirectory.mkdir();
Then you should make two String Var like below :
String filename = "yourImageName".jpg";
String dirpath =strpath + "/"+dirName + "/";
Make File Variable :
File storagePath = new File(dirpath);
File myImage = new File(storagePath, filename);
outStream = new FileOutputStream(myImage);
outStream.write(data);
outStream.close();
Hope this may helpful to you.
you just need a bitmap
and you have to pass a path to store the image
Bitmap b = pagesView.getDrawingCache();
b.compress(CompressFormat.JPEG, 100, new FileOutputStream(Environment.getExternalStorageDirectory() + "/NameOfFile.jpg"));
and you have to add permission in Manifest file..
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />