I have this snippet, which is creating image from view. File can be seen in file manager and accessible through code, but default android gallery app is not showing them.
Bitmap returnedBitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(),Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(returnedBitmap);
view.draw(canvas);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
returnedBitmap.compress(Bitmap.CompressFormat.PNG, 100, bytes);
Date now = new Date();
String path = Environment.getExternalStorageDirectory() + File.separator + "Download" + File.separator +now.getTime()+".png";
File f = new File(path);
try {
f.createNewFile();
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
fo.close();
} catch (Exception e) {
}
You need to add the file to the gallery. Try this code from the developer's website:
private void galleryAddPic(String path) {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(path);//your file path
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
}
Note make sure that you are not saving in the private memory of the app.
My experience is that to use MediaScanner is better, you can get the URI of the content stored in media database.
static final class PicScanner implements MediaScannerConnectionClient {
#SuppressWarnings("unused")
private static PicScanner mInstance;
private String mFilename;
private String mMimetype;
private MediaScannerConnection mConn;
public static void scan(Context ctx, File file, String mimetype) {
mInstance = new PicScanner (ctx, file, mimetype);
}
private PicScanner (Context ctx, File file, String mimetype) {
this.mFilename = file.getAbsolutePath();
mConn = new MediaScannerConnection(ctx, this);
mConn.connect();
}
#Override
public void onMediaScannerConnected() {
mConn.scanFile(mFilename, mMimetype);
}
#Override
public void onScanCompleted(String path, Uri uri) {
mConn.disconnect();
mInstance = null;
//notifyNewPicSavedLocally(path, uri);
}
}
Usage example:
PicScanner.scan(mContext, picFile, "image/jpeg"); //picFile should be access-able for other process
Related
I'm trying to save a RelativeLayout as a bitmap and insert it into the gallery, the code below throws this exception:
java.lang.NullPointerException
at java.io.File.<init>(File.java:282)
at maa.Fragements.ColorPaletteFragment.galleryAddPic(ColorPaletteFragment.java:344)
because the parameter imagePath of galleryAddPic method is empty or null
insert Image to gallery:
private void galleryAddPic(String imagePath) {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(imagePath);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
getActivity().sendBroadcast(mediaScanIntent);
}
saving the image:
#SuppressLint("StaticFieldLeak")
public class saveViewAsBitmap extends AsyncTask<RelativeLayout, String, String> {
#SuppressLint("SetTextI18n")
#Override
protected void onPreExecute() {
super.onPreExecute();
txt.setText("Saving image to gallery ...");
}
#Override
protected String doInBackground(RelativeLayout... relatives) {
String savedImagePath = null;
String imageFileName = "inColor" + System.currentTimeMillis() + ".png";
Bitmap image = getBitmapFromView(relatives[0]);
File storageDir = new File(
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
+ "/inColor Folder");
boolean success = true;
if (!storageDir.exists()) {
success = storageDir.mkdirs();
}
if (success) {
File imageFile = new File(storageDir, imageFileName);
savedImagePath = imageFile.getAbsolutePath();
try {
OutputStream fOut = new FileOutputStream(imageFile);
image.compress(Bitmap.CompressFormat.PNG, 100, fOut);
fOut.close();
} catch (Exception e) {
e.printStackTrace();
}
dialogLoading.dismiss();
}
return savedImagePath;
}
#Override
protected void onPostExecute(String path) {
super.onPostExecute(path);
galleryAddPic(path);
}
}
can anyone help me to get resolve this issue?
Make sure that you have
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
in Manifest file
when I save images, I want image to appear in the gallery, and not only inside the internal storage like apps wallpaper , facebook messenger
my code , On Click Button
holder.img_download.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
File dir = new File(Environment.getExternalStorageDirectory(), "/Wallpapers");
if(!dir.exists()) {
dir.mkdirs();
}
Bitmap bitmap = ((BitmapDrawable)holder.img_photo.getDrawable()).getBitmap();
saveImage(bitmap,dir);
}
});
funcation saveImage
private void saveImage(Bitmap finalBitmap,File dir) {
Random r = new Random();
String fname = "Image_" + r.nextInt(1000000) + ".jpg";
File file = new File(dir, fname);
if (file.exists()) file.delete();
try {
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
Toast toasty = Toasty.success(context,"Saved", Toast.LENGTH_LONG);
toasty.setGravity(Gravity.CENTER, 0, 0);
toasty.show();
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + dir)));
} catch (Exception e) {
e.printStackTrace();
}
}
I dont have any problem saving pictures but I want to show up in the gallery like image applications
Try this to add image in gallery:
public void addImageToGallery(final String filePath, final Context context) {
ContentValues contentValues = new ContentValues();
contentValues.put(Images.Media.DATE_TAKEN, System.currentTimeMillis());
contentValues.put(Images.Media.MIME_TYPE, "image/jpeg");
contentValues.put(MediaStore.MediaColumns.DATA, filePath);
context.getContentResolver().insert(Images.Media.EXTERNAL_CONTENT_URI, contentValues);
}
instead of File dir = new File(Environment.getExternalStorageDirectory(), "/Wallpapers");
use
File file = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), albumName);
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 need help with my code that save image to device on android but images are not showing in gallery i tried a lot of different code but not working i need implement it to this code
public class SaveImage extends Activity {
public void saveImage(ImageView imageView) {
Drawable image = imageView.getDrawable();
if(image != null && image instanceof BitmapDrawable) {
BitmapDrawable drawable = (BitmapDrawable) image;
Bitmap bitmap = drawable.getBitmap();
File dir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "Picster");
dir.mkdirs();
Date now = new Date();
String timestamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(now);
String path = dir.getPath() + File.separator;
File file = new File(path + "IMG_" + timestamp + ".jpg");
try {
FileOutputStream stream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
stream.flush();
stream.close();
galleryAddPic(file.toString());
} catch (Exception e) {
// TODO: handle exception
}
}
}
public void galleryAddPic(String file) {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(file);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
}
}
i call it in other activity like this
final ImageView image = (ImageView) findViewById(R.id.messageImageView);
Uri imageUri = getIntent().getData();
Picasso.with(this).load(imageUri.toString()).into(image);
final Button button = (Button) findViewById(R.id.button_id);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
SaveImage cls2= new SaveImage();
cls2.saveImage(image);
}
});
look on my updated code i add new void galleryAddpic and call it in TRY block it save pictures but still not show in gallery
You just have to add some lines of code to show that image in gallery with instant effect.
Add this code after your file has been created successfully.
Code :
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
Example :
private void galleryAddPic() {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(mCurrentPhotoPath);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
}
Request the media scanner to scan a file and add it to the media database.
VISIT THIS LINK FOR MORE DETAILS :
I am working on a application in which I have to click the image from the camera and save it into directory.I am able to create directory named MyPersonalFolder and also images are going into it but when I am trying to open that image to see, it doesn't open and shows the message that that image cannot be opened. here is my code. Can anyone please tell me what mistake I am doing here.
I have also mentioned permissions in manifest .
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
public class Camera extends Activity{
private static final String TAG = "Camera";
private static final int CAMERA_PIC_REQUEST = 1111;
Button click , share;
ImageView image;
String to_send;
String filename;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.camera);
image = (ImageView)findViewById(R.id.image);
share = (Button)findViewById(R.id.share);
click = (Button)findViewById(R.id.click);
click.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAMERA_PIC_REQUEST);
}
});
share.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
BitmapDrawable bitmapDrawable = (BitmapDrawable)image.getDrawable();
Bitmap bitmap = bitmapDrawable.getBitmap();
// Save this bitmap to a file.
File cache = getApplicationContext().getExternalCacheDir();
File sharefile = new File(cache, "toshare.png");
try {
FileOutputStream out = new FileOutputStream(sharefile);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
} catch (IOException e) {
}
// Now send it out to share
Intent share = new Intent(android.content.Intent.ACTION_SEND);
share.setType("image/*");
share.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + sharefile.getAbsolutePath()));
try {
startActivity(Intent.createChooser(share, "Share photo"));
} catch (Exception e) {
}
/*Intent share = new Intent(Intent.ACTION_SEND);
share.setType("text/plain");
//String to_send = null;
share.putExtra(Intent.EXTRA_TEXT, to_send);
startActivity(Intent.createChooser(share, "Share using..."));*/
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
FileOutputStream outStream = null;
if (requestCode == CAMERA_PIC_REQUEST) {
//2
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
image.setImageBitmap(thumbnail);
//3
share.setVisibility(0);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
//4
try {
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File (sdCard.getAbsolutePath() + "/MyPersonalFolder");
dir.mkdirs();
String fileName = String.format("%d.jpg", System.currentTimeMillis());
File outFile = new File(dir, fileName);
outStream = new FileOutputStream(outFile);
//outStream.write(data[0]);
outStream.flush();
outStream.close();
//Log.d(TAG, "onPictureTaken - wrote bytes: " + data.length + " to " + outFile.getAbsolutePath());
refreshGallery(outFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
/*try {
file.createNewFile();
FileOutputStream fo = new FileOutputStream(file);
//5
fo.write(bytes.toByteArray());
fo.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();*/
}
}
}
private void refreshGallery(File file) {
Intent mediaScanIntent = new Intent( Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
mediaScanIntent.setData(Uri.fromFile(file));
sendBroadcast(mediaScanIntent);
}
}
You will need to use MediaScanner to notify the system of the new file/directory. You can try something like this after creating and saving the new file:
/**
* Adds the new photo/video to the device gallery, else it will remain only visible via sd card
*
* #param path
*/
public static void addToGallery(Context context, String path) {
MediaScanner scanner = new MediaScanner(path, null);
MediaScannerConnection connection = new MediaScannerConnection(context, scanner);
scanner.connection = connection;
connection.connect();
}
/**
* Scans the sd card for new videos/images and adds them to the gallery
*/
private static final class MediaScanner implements MediaScannerConnection.MediaScannerConnectionClient {
private final String path;
private final String mimeType;
MediaScannerConnection connection;
public MediaScanner(String path, String mimeType) {
this.path = path;
this.mimeType = mimeType;
}
#Override
public void onMediaScannerConnected() {
connection.scanFile(path, mimeType);
}
#Override
public void onScanCompleted(String path, Uri uri) {
connection.disconnect();
}
}
EDIT:
You are also forgetting to write the byte array to the file specified in the output stream, like in the code that you have commented out. Try this at the end just before you refresh the gallery:
outStream = new FileOutputStream(outFile);
outStream.write(bytes.toByteArray()); //this is the line you had missing
outStream.flush();
outStream.close();
Also take note that using Intent.ACTION_MEDIA_SCANNER_SCAN_FILE to refresh the gallery can also present you with some security issues on kitkat (cant remember exactly what the issues were). So just make sure you test it on kitkat device to confirm that it works correctly