Save Bitmap as a jpeg image - android

In my android application i generate a qr code then save it as a jpeg image, i use this code:
imageView = (ImageView) findViewById(R.id.iv);
final Bitmap bitmap = getIntent().getParcelableExtra("pic");
imageView.setImageBitmap(bitmap);
save = (Button) findViewById(R.id.save);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String path = Environment.getExternalStorageDirectory().toString();
OutputStream fOutputStream = null;
File file = new File(path + "/Captures/", "screen.jpg");
if (!file.exists()) {
file.mkdirs();
}
try {
fOutputStream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOutputStream);
fOutputStream.flush();
fOutputStream.close();
MediaStore.Images.Media.insertImage(getContentResolver(), file.getAbsolutePath(), file.getName(), file.getName());
} catch (FileNotFoundException e) {
e.printStackTrace();
return;
} catch (IOException e) {
e.printStackTrace();
return;
}
}
});
but it always catches an exception at the line:
fOutputStream = new FileOutputStream(file);
what caused this problem???

what caused this problem???
The statement file.mkdirs(); created a directory by the name screen.jpg. The FileOutputStream could not create a file with name screen.jpg while there is a directory by that name is found. So you got:
java.io.FileNotFoundException
Could you please replace following snippets:
File file = new File(path + "/Captures/", "screen.jpg");
if (!file.exists()) {
file.mkdirs();
}
by the following snippets:
String dirPath = path + "/Captures/";
File dirFile = new File(dirPath);
if(!dirFile.exists()){
dirFile.mkdirs();
}
File file = new File(dirFile, "screen.jpg");
and see the results?

Related

How to save image to pictures folder in android

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");

How to store background image from imageView in bitmap?

I am trying to store my image from imageView in bitmap, so that I can store it in the gallery of the android device. Every time I save an image, the background of the imageView is not stored. What am I missing?
Here is my code:
ImageView imageView = (ImageView) findViewById(R.id.img);
imageView.setBackgroundResource(R.drawable.img1);
BitmapDrawable draw = (BitmapDrawable) imageView.getDrawable();
Bitmap bitmap = draw.getBitmap();
Code to store the image into the gallery is:
FileOutputStream outStream = null;
File dir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
"MyAlbum");
if (!dir.exists()) {
if (!dir.mkdirs()) {
Log.d("MyAlbum", "failed to create directory");
Toast.makeText(MainActivity.this, "Failed to make directory", Toast.LENGTH_SHORT).show();
}
}
String fileName = String.format("%d.jpg", System.currentTimeMillis());
File outFile = new File(dir, fileName);
try {
outStream = new FileOutputStream(outFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
outStream.flush();
outStream.close();
Toast.makeText(getApplicationContext(), "PICTURE SAVED", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
intent.setData(Uri.fromFile(dir));
sendBroadcast(intent);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
You can take a screenshot of this view (ImageView) in this case, it will simply take what's drawn on this view at this moment and turn it into a bitmap you can save.
Answer is mentioned here already.
The magical part is that
ImageView yourImageView = .. // Get reference it to your view.
yourImageView.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(yourImageView.getDrawingCache());
yourImageView.setDrawingCacheEnabled(false);
Ta-da you can use your snapshot btimap.
you can try this out,
private void saveImageToStorage(Bitmap finalBitmap, String image_name) {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root);
myDir.mkdirs();
String fname = "Image-" + image_name+ ".jpg";
File file = new File(myDir, fname);
if (file.exists()) file.delete();
Log.i("LOAD", root + fname);
try {
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Happy coding :-)

write image in external directory android

How to write image in phone directory. Directory is created but i could not write image in this folder. Here is my code .please check if i am doing something wrong thanks in advance.
Bitmap bitmap;
String directory = new_path; // I am getting path here of image like sdcard/0/emulated/image.jpg
String folder_name = "abc"
bitmap = BitmapFactory.decodeFile(directory);
iv_6.setImageBitmap(bitmap); // image displayed here but not saving in directory.
try {
File f = new File(Environment.getExternalStorageDirectory()
+ File.separator +folder_name);
f.mkdirs();
FileOutputStream fo = new FileOutputStream(f);
bitmap.compress(Bitmap.CompressFormat.JPEG, 40, fo);
fo.close();
}catch (Exception e)
{
e.printStackTrace();
}
public void savePng(Bitmap bitmap, String filePath) {
try {
File temp = new File(filePath);
FileOutputStream os = new FileOutputStream(temp + ".png");
bitmap.compress(Bitmap.CompressFormat.PNG, 50, os);
os.flush();
os.close();
} catch (Exception e) {
e.printStackTrace();
}
}

Android app Image is not saving in specified Sd Card folder after Crop, Showing empty folder

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"/>

Save Bitmap to SD Card

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" />

Categories

Resources