I have made an app that uses the filter image and save in sdcard it's working good but I want to save image in two resolution high and low, I have never tried on resolution, Any one one can help that how to save in these both resolution? My code is below
private void saveBitmap(Bitmap bmp, String fileName, int resolution, String resolutionQuality) {
// File f = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + fileName + ".png");
File f = new File(Environment.getExternalStorageDirectory() + "FiltureImages");
if (!f.exists()) {
File wallpaperDirectory = new File("/sdcard/FiltureImages/");
wallpaperDirectory.mkdirs();
}
File file = new File(new File("/sdcard/FiltureImages/"), fileName + resolutionQuality + ".png");
if (file.exists()) {
file.delete();
}
try {
fos = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.PNG, resolution, fos);
Toast.makeText(mActivity, "Image save successfully", Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
Call like this saveBitmap(bm, "high", "low", 100, 0, "quality");
Quality range from 0 -100
Note: change Bitmap.CompressFormat.PNG to Bitmap.CompressFormat.JPEG beacuse quality works with JPEG format.
private void saveBitmap(Bitmap bmp, String fileNameHigh, String fileNameLow, int resolutionHigh, int resolutionLow, String resolutionQuality) {
File f = new File(Environment.getExternalStorageDirectory() + "FiltureImages");
if (!f.exists()) {
f.mkdirs();
}
File file = new File(f, fileNameHigh + resolutionQuality + ".png");
if (file.exists()) {
file.delete();
}
File file1 = new File(f, fileNameLow + resolutionQuality + ".png");
if (file1.exists()) {
file1.delete();
}
try {
FileOutputStream high = new FileOutputStream(file);
FileOutputStream low = new FileOutputStream(file1);
bmp.compress(Bitmap.CompressFormat.JPEG, resolutionHigh, high);
bmp.compress(Bitmap.CompressFormat.JPEG, resolutionLow, low);
Toast.makeText(this, "Image save successfully", Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
Toast.makeText(this, "Image save falid", Toast.LENGTH_SHORT).show();
}
}
Create a second bitmap with an alternate resolution this way and call scaledBmp.compress() into a new file.
Bitmap scaledBmp = Bitmap.createScaledBitmap(bmp, newWidth, newHeight, false);
Related
I am saving an image into sdcard, but I want that the directory folder will be automatically shown in the gallery and the image on the folder. Whenever I save the image I am rebooting my phone for the directory folder to be shown in the gallery. Is it my code that has a problem? or the phone? Please help me. Thank you so much. I dont know what to do
here's my code:
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
mTempDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/" + "PixiePhotos" + "/";
prepareDirectory();
save.setOnClickListener(new View.OnClickListener() {
#SuppressLint("ShowToast")
#SuppressWarnings("deprecation")
public void onClick(View v) {
Log.v(TAG, "Save Tab Clicked");
viewBitmap = Bitmap.createBitmap(500, 500, Bitmap.Config.ARGB_8888);
canvas = new Canvas(viewBitmap);
tapimageview.draw(canvas);
canvas.drawBitmap(bp, 0, 0, paint);
canvas.drawBitmap(drawingBitmap, matrix, paint);
canvas.drawBitmap(bmpstickers, matrix, paint);
//tapimageview.setImageBitmap(mBitmapDrawable.getBitmap());
try {
mBitmapDrawable = new BitmapDrawable(viewBitmap);
mCurrent = "PXD_" + new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date()) + ".jpg";
bp1 = mBitmapDrawable.getBitmap();
tapimageview.setImageBitmap(bp1);
mNewSaving = ((BitmapDrawable) mBitmapDrawable).getBitmap();
String FtoSave = mTempDir + mCurrent;
File mFile = new File(FtoSave);
mFileOutputStream = new FileOutputStream(mFile);
mNewSaving.compress(CompressFormat.JPEG, 100, mFileOutputStream);
mFileOutputStream.flush();
mFileOutputStream.close();
} catch (FileNotFoundException e) {
Log.v(TAG, "FileNotFoundExceptionError " + e.toString());
} catch (IOException e) {
Log.v(TAG, "IOExceptionError " + e.toString());
}
Toast.makeText(getApplicationContext(), "Your photo has been saved", Toast.LENGTH_LONG).show();
}
});
}
private boolean prepareDirectory() {
try {
if (makeDirectory()) {
return true;
} else {
return false;
}
} catch (Exception e) {
e.printStackTrace();
//Toast.makeText(this, getString(R.string.sdcard_error), 1000).show();
return false;
}
}
private boolean makeDirectory() {
File mTempFile = new File(mTempDir);
if (!mTempFile.exists()) {
mTempFile.mkdirs();
}
if (mTempFile.isDirectory()) {
File[] mFiles = mTempFile.listFiles();
for (File mEveryFile : mFiles) {
if (!mEveryFile.delete()) {
//System.out.println(getString(R.string.failed_to_delete) + mEveryFile);
}
}
}
return (mTempFile.isDirectory());
}
Try this:
private boolean storeImage(Bitmap imageData, String filename) {
//get path to external storage (SD card)
String iconsStoragePath = Environment.getExternalStorageDirectory() + "/myAppDir/myImages/"
File sdIconStorageDir = new File(iconsStoragePath);
//create storage directories, if they don't exist
sdIconStorageDir.mkdirs();
try {
String filePath = sdIconStorageDir.toString() + filename;
FileOutputStream fileOutputStream = new FileOutputStream(filePath);
BufferedOutputStream bos = new BufferedOutputStream(fileOutputStream);
//choose another format if PNG doesn't suit you
imageData.compress(CompressFormat.PNG, 100, bos);
bos.flush();
bos.close();
} catch (FileNotFoundException e) {
Log.w("TAG", "Error saving image file: " + e.getMessage());
return false;
} catch (IOException e) {
Log.w("TAG", "Error saving image file: " + e.getMessage());
return false;
}
return true;
}
Don't forget to add Storage Permissions
Since this is operation that saves data on external memory, it requires AndroidManifest.xml permissions:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
try it out
void saveImage() {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/saved_images");
String fname = "Image.jpg";
File file = new File (myDir, fname);
if (file.exists ()) file.delete ();
try {
FileOutputStream out = new FileOutputStream(file);
myBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
and add permission in your maniefest file
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
The problem is not with the code ...
what happens over here is
After downloading the file on the sdcard the gallery is not notified with new file added or downloaded to the system
What you need to do is you have to manually Notify the gallery that ...okhay gallery file is added please show ..:)
For that you have to use MediaScannerConnection
Download the file ,scan the particular file and it will be shown in the gallery
and you are done:)
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!
I have a problem to save Bitmaps into files.
My method is like this:
private File savebitmap(Bitmap bmp) {
String extStorageDirectory = Environment.getExternalStorageDirectory()
.toString();
OutputStream outStream = null;
File file = new File(bmp + ".png");
if (file.exists()) {
file.delete();
file = new File(extStorageDirectory, bmp + ".png");
Log.e("file exist", "" + file + ",Bitmap= " + bmp);
}
try {
outStream = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.PNG, 100, outStream);
outStream.flush();
outStream.close();
} catch (Exception e) {
e.printStackTrace();
}
Log.e("file", "" + file);
return file;
}
It gives me error of file.I am calling this method like this:
Drawable d = iv.getDrawable();
Bitmap bitmap = ((BitmapDrawable) d).getBitmap();
File file = savebitmap(bitmap);
Please help me...
I try to make some corrections on your code
I assume that you want to use filename instead of bitmap as parameter
private File savebitmap(String filename) {
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
OutputStream outStream = null;
File file = new File(filename + ".png");
if (file.exists()) {
file.delete();
file = new File(extStorageDirectory, filename + ".png");
Log.e("file exist", "" + file + ",Bitmap= " + filename);
}
try {
// make a new bitmap from your file
Bitmap bitmap = BitmapFactory.decodeFile(file.getName());
outStream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
outStream.flush();
outStream.close();
} catch (Exception e) {
e.printStackTrace();
}
Log.e("file", "" + file);
return file;
}
You can't write like this
File file = new File(bmp + ".png");
and this line is also wrong
file = new File(extStorageDirectory, bmp + ".png");
You have to give string value and not bitmap.
File file = new File(filename + ".png");
Change
File file = new File(bmp + ".png");
to
File file = new File(extStorageDirectory,"bmp.png");
like you did nearly the second time.
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" />
i'm using the following code for saving the image
FrameLayout mainLayout = (FrameLayout) findViewById(R.id.frame);
// File root = Environment.getExternalStorageDirectory();
// File file = new File(root, "androidlife.jpg");
// File file = new File(Environment.getExternalStorageDirectory()
// + File.separator + "/test.jpg");
Random fCount = new Random();
// for (int i = 0; i < 10; i++) { Comment by Lucifer
int roll = fCount.nextInt(600) + 1;
//System.out.println(roll);
File file = new File(Environment.getExternalStorageDirectory()
+ File.separator + "/test" + String.valueOf(roll) +".jpg" );
Bitmap b = Bitmap.createBitmap(mainLayout.getWidth(),
mainLayout.getHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
mainLayout.draw(c);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
if (fos != null) {
b.compress(Bitmap.CompressFormat.JPEG, 90, fos);
fos.close();
}
} catch (Exception e) {
e.printStackTrace();
}
// } Comment by Lucifer
it save the image perfectly but overwrite when i press the save button twice...What can be the issue? Any sugestion??
File file = new File(Environment.getExternalStorageDirectory()
+ File.separator + "/test.jpg");
if(!file.exists()){
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{
file.delete();
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Bitmap b = Bitmap.createBitmap(mainLayout.getWidth(),
mainLayout.getHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
mainLayout.draw(c);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
if (fos != null) {
b.compress(Bitmap.CompressFormat.JPEG, 90, fos);
fos.close();
}
} catch (Exception e) {
e.printStackTrace();
}
You have given a static file name.
File file = new File(Environment.getExternalStorageDirectory()
+ File.separator + "/test.jpg");
So, Everytime it is going to create a image with test.jpg name and at a same location. The only logic you need to implement is to change your file name to be a dynamic file name. You can try it in this way
static int fCount = 0;
File file = new File(Environment.getExternalStorageDirectory()
+ File.separator + "/test" + String.valueOf(fCount++) +".jpg" );
Now above line is going to create a new file every time, starting with name test0.jpg, test1.jpg ... and so on.
But this could create a problem when you close your application and restart your application. Because it will going to start again from 0 counter.
So i suggest you to go with a random number contacatination with file name.
sticker_view.setLocked(true);
sticker_view.setDrawingCacheEnabled(true);
Bitmap bitmap = sticker_view.getDrawingCache();
Log.e("BITMAP", "onOptionsItemSelected: " + bitmap);
String root = Environment.getExternalStorageDirectory().toString();
File newDir = new File(root + "/Edited Image");
newDir.mkdirs();
Random gen = new Random();
int n = 10000;
n = gen.nextInt(n);
String photoName = "Image-" + n + ".jpg";
Log.e("PHOTONAME", "onOptionsItemSelected: " + photoName);
File file = new File(newDir, photoName);
String filePath = file.getAbsolutePath();
Log.e("FILEPATH", "onOptionsItemSelected: " + filePath);
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(EditActivity.this, "Image Already Exist.", Toast.LENGTH_SHORT).show();
} else {
file.delete();
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
FileOutputStream out = new FileOutputStream(file);
Log.e("OUT", "onOptionsItemSelected: " + out);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
bitmap.recycle();
Toast.makeText(EditActivity.this, "Saved In Edited Image.", Toast.LENGTH_SHORT).show();
item.setVisible(false);
MediaScannerConnection.scanFile(EditActivity.this, new String[]{file.getAbsolutePath()},
null, new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("ExternalStorage", "Scanned " + path + ":");
Log.i("ExternalStorage", "-> uri=" + uri);
}
});
Intent intent = new Intent();
intent.setAction("URI");
intent.putExtra("uri", filePath);
sendBroadcast(intent);
finish();
} catch (Exception e) {
e.printStackTrace();
}
}
You can just add System.currentTimeMillis() in the name of your file name to get a complete unique file name. This will add current time in milliseconds since epoch to your file name and unless you can create more than one file in a single millisecond, no overwrite will be done.