I am using ImageView in my android application here i show the images from webservice so i am using UrlImageViewHelper. i want to store this image into android Gallery files.
my images like:
String Images = dataExtra.get("images").toString();
System.out.println("image URL"+Images);
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(Images);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
i tried like this.. but its not working. Any one can help me how to store these Images into Android Gallery?
i got solution for this problem, Here my answer
private void saveImagesIntoGallery(){
BitmapDrawable drawable = (BitmapDrawable) imageView.getDrawable();
Bitmap bitmap = drawable.getBitmap();
// File sdCardDirectory = Environment.getExternalStorageDirectory();// its stores under sdcard not in a specific path
String sdCardDirectory = Environment.getExternalStorageDirectory().toString()+"/Pictures/";
String url = arrayForImages[i].toString();
String file = url.substring(url.lastIndexOf('/')+1);
System.out.println("PATH NAME"+sdCardDirectory);
File image = new File(sdCardDirectory, file);
boolean success = false;
// Encode the file as a PNG image.
FileOutputStream outStream;
try {
outStream = new FileOutputStream(image);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
/* 100 to keep full quality of the image */
outStream.flush();
outStream.close();
success = true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (success) {
Toast.makeText(getApplicationContext(), "Image saved with success",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),
"Error during image saving", Toast.LENGTH_LONG).show();
}
}
Are you sure that the gallery is the best place to store images of webservice?
If you wanted to save to internal storage:
public void saveBitmap(String name, Bitmap bitmap){
if(bitmap!=null && name!=null){
FileOutputStream fos;
if(bitmap!=null){
try {
fos = openFileOutput(name, Context.MODE_PRIVATE);
bitmap.compress(CompressFormat.JPEG, 90, fos);
} catch (FileNotFoundException e) {}
}
}
}
To gallery, i have not examples here. But search a little;)
Related
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 :-)
I am working in android studio. Building an app in which i am using a camera. When i run my app the app works fine. I capture the image it does captured the image. But the folder i created is not showing in my gallery. I am saving images in my local storage and not in SD CARD. I was very curious that why the folder is not created as it doesn't gives me any error so it should be in my gallery. So i restarted my device and after restarting i can see the folder in my gallery and the images taken in it. I again open the app and took images from it but again the images were not shown in the folder.
Below is my code in which i am making ta directory for saving images
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)
{
if(resultCode == Activity.RESULT_OK)
{
Bitmap bmp = (Bitmap)data.getExtras().get("data");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] byteArray = stream.toByteArray();
// convert byte array to Bitmap
Bitmap bitmap = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
if(isStoragePermissionGranted())
{
SaveImage(bitmap);
}
}
}
private void SaveImage(Bitmap finalBitmap) {
String root = Environment.getExternalStorageDirectory().getAbsolutePath().toString();
Log.v(LOG_TAG, root);
File myDir = new File(root + "/captured_images");
myDir.mkdirs();
Random generator = new Random();
int n = 1000;
n = generator.nextInt(n);
String fname = "Image-" + n + ".jpg";
File file = new File(myDir,fname);
if (file.exists())file.delete();
try {
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG,100,out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Below is the picture of my debugging
**Note: **
As i am using native camera so the pictures are saved in the camera roll folder i.e. the default folder in my device. But the image saved there is not the compressed one, the compress image should be saved in my created folder.
I am stuck to it and don't know what to do.
Any help would be highly appreciated.
You need to invoke scanFile(Context context, String[] paths, String[] mimeTypes, MediaScannerConnection.OnScanCompletedListener callback) method of MediaScannerConnection.
MediaScannerConnection provides a way for applications to pass a newly created or downloaded media file to the media scanner service. This will update your folder with the newly saved media.
private void SaveImage(Bitmap finalBitmap) {
//....
if(!storageDir.exists()){
storageDir.mkdirs();
}
//...
file.createNewFile();
try {
MediaScannerConnection.scanFile(context, new String[] {file.getPath()} , new String[]{"image/*"}, null);
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG,100,out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
try this
private void saveBitmap(Bitmap bitmap) {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = timeStamp + ".jpg";
File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
final String fileLoc = storageDir.getAbsolutePath() + "/folderName/" + imageFileName;
File file = new File(fileLoc);
OutputStream os = null;
try {
os = new BufferedOutputStream(new FileOutputStream(file));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os);
try {`enter code here`
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
I created a bitmap with text and I can view it in an Imageview, but when I save the Bitmap I only get a black image. I have spend three hours looking at similar questions but none of the worked for me. Here is the code.
Thanks for any help.
public void createBitmap(){
Bitmap LabelBitmap;
FileOutputStream fos = null;
//create Text Bitmap
LabelBitmap = textAsBitmap(this,"BRO D 0813","fonts/arialbd.ttf", 4, Color.BLACK);
//load bitmap in to Imageview
ImageView myImageView = (ImageView) findViewById(R.id.imageView);
myImageView.setImageBitmap(LabelBitmap);
// save bitmap
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/myfolder");
myDir.mkdirs();
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
LabelBitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
if (!myDir.exists()) {
myDir.mkdir();
}
File myDirFile = new File(root +"/myfolder/mybitmap.jpg");
try {
if(myDirFile.exists()){
myDirFile.delete();
}
myDirFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
try {
fos = new FileOutputStream(myDirFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
fos.write(bytes.toByteArray());
fos.flush();
fos.close();
Toast.makeText(this, "Image saved", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
}
JPEG Image has a black background by default, so if your text color is also black you will get a black image. If your image has no background color, you must save it as PNG. Change as following and have a try:
LabelBitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
to:
LabelBitmap.compress(Bitmap.CompressFormat.PNG, 100, bytes);
I was Developing an application which will have image on image view .
My need:
What i need is When i click the button then it should store the image that exist in the image view to the sd card(emulator).
Here is how i used:(but no expected results)
Button btnWriteSDFile = (Button) findViewById(R.id.btnWriteSDFile);
btnWriteSDFile.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
ImageView myImage = (ImageView) findViewById(R.id.imageView1);
BitmapDrawable drawable = (BitmapDrawable) myImage.getDrawable();
Bitmap bitmap = drawable.getBitmap();
File sdCardDirectory = Environment.getExternalStorageDirectory();
File image = new File(sdCardDirectory, "image.png");
boolean success = false;
// Encode the file as a PNG image.
FileOutputStream outStream;
try {
outStream = new FileOutputStream(image);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
outStream.flush();
outStream.close();
success = true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (success) {
Toast.makeText(getApplicationContext(), "Image saved with success",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),
"Error during image saving", Toast.LENGTH_LONG).show();
}
}
});
In my above code i didnt get any error
It simply Shows that "save file in mnt/sd/image.png" but no images found.
It would be appreciable if some one helps me to get me out from this rid.
**
"Found out where the exact issues": My program was running perfectly
# 1st time if i click button and check in gallery means there is no
image but once i close and open the emulator then there is a image.But
i need to see the image as soon as updated how to do this any ideas?
**
Your code looks good, but in order to write something to external storage, you should have the following permission declared in the manifest:
android.permission.WRITE_EXTERNAL_STORAGE
if you use some thing like
ImageView myImage = (ImageView) findViewById(R.id.imageView1);
myImage .setDrawingCacheEnabled(true);
myImage .buildDrawingCache();
Bitmap bitmap = myImage .getDrawingCache();
File sdCardDirectory = Environment.getExternalStorageDirectory();
File image = new File(sdCardDirectory, "image.png");
boolean success = false;
// Encode the file as a PNG image.
FileOutputStream outStream;
try {
outStream = new FileOutputStream(image);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
outStream.flush();
outStream.close();
success = true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (success) {
Toast.makeText(getApplicationContext(), "Image saved with success",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),
"Error during image saving", Toast.LENGTH_LONG).show();
}
}
});
and please set the following permission in androidManifest.xml
android.permission.WRITE_EXTERNAL_STORAGE
Try below code to take a screenshot
private static Bitmap takeScreenShot()
{
Bitmap bitmap = ((BitmapDrawable)image.getDrawable()).getBitmap();
return bitmap;
}
For saving
private File saveBitmap(Bitmap bitmap)
{
File snapShot=null;
try
{
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 40, bytes);
File f = new File(Environment.getExternalStorageDirectory()
+ File.separator + "test.jpg");
f.createNewFile();
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
fo.close();
} catch (Exception e)
{
e.printStackTrace();
}
return snapShot;
}
Need to give permission
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
I am trying to save bitmap to sd cart, but it saved like black image.
This code shows like I am creating bitmap
mStoryView.setDrawingCacheEnabled(true);
mStoryView.buildDrawingCache();
Bitmap result = Bitmap.createBitmap(mStoryView.getDrawingCache());
mStoryView.setDrawingCacheEnabled(false);
result = ImageUtil.saveStoryImage(this,result);
On this step bitmap looks good ( I set it on background view).
public static Bitmap saveStoryImage(Context context, Bitmap result) {
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File file = new File(extStorageDirectory, "test.png");
FileOutputStream outStream = null;
try {
outStream = new FileOutputStream(file);
boolean b = result.compress(Bitmap.CompressFormat.PNG, 100, outStream);
outStream.flush();
outStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
After that I go to my sd card ondevice and saw black image.
What is the problem?