Rewrite code android - android

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 :

Related

Bitmap Share Intent

I am trying to convert entire CardView into an Image and then I want to share it using different apps.
PROBLEM
cardView.setDrawingCacheEnabled(true);
cardView.measure(View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED),
View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED));
cardView.layout(0,0, cardView.getMeasuredWidth(), cardView.getMeasuredHeight());
cardView.buildDrawingCache(true);
bitmap = Bitmap.createBitmap(cardView.getDrawingCache());
cardView.setDrawingCacheEnabled(false);
String path = MediaStore.Images.Media.insertImage(DetailedActivity.this.getContentResolver(),bitmap,"quote",null);
uri = Uri.parse(path);
Thing is I am getting cardview converted into bitmap but while getting uri from bitmap it is returning null path. so while converting Uri it is giving NULL POINTER EXCEPTION.
Below is the list of permissions I provided.
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.MEDIA_CONTENT_CONTROL"
tools:ignore="ProtectedPermissions" />
CardView XML
If I give the CardView a defined hardcoded values for Height and Width of a CardView it is working but when I use
android:layout_width="match_parent"
android:layout_height="match_parent"
With the code shown above it is giving NULL_POINTER_EXCEPTION.
QUERIES
1. How can I make it work?
2. Is there any other way to do this?
So if I get it right, the URI path is stored in uri variable. The null error happens because you didn't initialise that uri string. You can do this:
String uri = new String() // -> if there is still an error here, replace String() with String(this) or String(activity_your_name.this)
Intent intent = new Intent(this, activity_output.class); // -> here you add the activity where you send the URI to
intent.putExtra("URI", uri);
and on the other activities you extract the URI through:
//Getting the URI from previous activity:
path = getIntent().getExtra("URI");
//Initialising the File form your URI
File StringToBitmap = new File;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
StringToBitmap = new File(path, String.valueOf(options));
//Your bitmap will be stored in mBitmaps
mBitmaps = BitmapFactory.decodeFile(path);
//The next part is extra, if you want to display your bitmap into an ImageView
ImageView iv = new ImageView();
iv = findViewById(R.id.your_id);
iv.setImageBitmap(mBitmaps);
This code worked to me for something very similar. And about that NULL EXCEPTION, every time you get it, try to see if you initialised all your objects correctly. Hope this helps.
Try This:
public Bitmap getScreenShot(View view) {
view.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(view.getDrawingCache());
view.setDrawingCacheEnabled(false);
return bitmap;
}
public void onShareImage(Bitmap bitmap) {
#SuppressLint("SimpleDateFormat") String fileName = "IMG_" + new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()) + ".PNG";
storeScreenShot(bitmap, fileName);
Uri imgUri = Uri.fromFile(new File(VarName.SCREENSHOT_DIRECTORY + "/" + fileName));
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
shareIntent.setType("image/*");
shareIntent.putExtra(Intent.EXTRA_STREAM, imgUri);
shareIntent.putExtra(Intent.EXTRA_TEXT, VarName.DRESS_ME_SHARE_MASSAGE_HEADER + "\n" + VarName.DRESS_ME_SHARE_APP_LINK);
startActivity(Intent.createChooser(shareIntent, "Share Image"));
}
public void storeScreenShot(Bitmap bm, String fileName) {
File dir = new File(VarName.SCREENSHOT_DIRECTORY);
if (!dir.exists()) {
dir.mkdirs();
File file = new File(dir.getAbsolutePath(), ".nomedia");
try {
file.createNewFile();
final Intent scanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
final Uri contentUri = Uri.fromFile(file);
scanIntent.setData(contentUri);
sendBroadcast(scanIntent);
} catch (IOException e) {
e.printStackTrace();
}
}
File file = new File(VarName.SCREENSHOT_DIRECTORY, fileName);
try {
FileOutputStream fOut = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.PNG, 100, fOut);
fOut.flush();
fOut.close();
file.createNewFile();
final Intent scanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
final Uri contentUri = Uri.fromFile(file);
scanIntent.setData(contentUri);
sendBroadcast(scanIntent);
} catch (Exception e) {
e.printStackTrace();
}
}
Now you Just need to call function.
Bitmap bitmap = getScreenShot(cardView);
onShareImage(bitmap);

How to create separate folder for captured images with losing quality

Hi i am trying to create separate folder for captured images with out losing quality using below code but i am getting exception android.os.FileUriExposedException: file:///storage/emulated/0/myFolder/photo_20180504_102426.png exposed beyond app through ClipData.Item.getUri()
what did do mi-stack can some one correct my code
code:
String folder_main = "myFolder";
File f = new File(Environment.getExternalStorageDirectory(), folder_main);
if (!f.exists()) {
f.mkdirs();
}
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File file = new File(Environment.getExternalStorageDirectory(), "/myFolder" + "/photo_" + timeStamp + ".png");
imageUri = Uri.fromFile(file);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, Constants.CAMERA_REQUEST_CODE);
private void onCaptureImageResult(Intent data) {
try {
Bitmap thumbnail = MediaStore.Images.Media.getBitmap(getContentResolver(), imageUri);
CircleImageView circleImageView = findViewById(formFields.get(imagePosition).getId());
circleImageView.setImageBitmap(thumbnail);
}
Put This on Your oncreate()
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());

How to show Picture into a activity after taken and saved from custom camera

In My app I am taking picture and I am successfully saving it in the gallery after compressing it. Now I want to show it into other activity, so that user can share it or view it at least. So How can I do that.
Following is my code which is saving picture and just after saving it, it shows ad , and on the adClosed event I want to send that taken picture to other activity , How Can I do that. My code just goes like this ..
File storagePath = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+ File.separator + "MyAnimals");
storagePath.mkdirs();
String finalName = Long.toString(System.currentTimeMillis());
//this snippet is saving image And I am showing ad after saving picture
File myImage = new File(storagePath, finalName + ".jpg");
String photoPath = Environment.getExternalStorageDirectory().getAbsolutePath() +"/" + finalName + ".jpg";
try {
FileOutputStream fos = new FileOutputStream(myImage);
newImage.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.close();
//refreshing gallery
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
mediaScanIntent.setData(Uri.fromFile(myImage));
sendBroadcast(mediaScanIntent);
} catch (IOException e) {
Toast.makeText(this, "Pic not saved", Toast.LENGTH_SHORT).show();
return;
}
Toast.makeText(this, "Pic saved in: " + photoPath, Toast.LENGTH_SHORT).show();
displayInterstitial();
interstitial.setAdListener(new AdListener() {
#Override
public void onAdClosed() {
Log.v("Add time");
Intent intent = new Intent(CameraActivity.this,ShowCapturedImage.class);
//Now How to send the saved picture to the image view of other activity?
startActivity(intent);
super.onAdClosed();
}
});
1) put taken image path in intent
2) get path in other activity and set it in imageview
public static final int REQUEST_CODE_FROM_CAMERA = 112;
private Uri fileUri;
String image_path = "";
//Catch image from below function
private void fromCamera() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
Log.d("FROM CAMERA CLICKED file uri", fileUri.getPath());
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// start the image capture Intent
startActivityForResult(intent, REQUEST_CODE_FROM_CAMERA);
}
//On Activity result store image path
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE_FROM_CAMERA
&& resultCode == Activity.RESULT_OK) {
try {
image_path = fileUri.getPath();
} catch (NullPointerException e) {
e.printStackTrace();
}
}
}
On Click of any button
Intent iSecond=new Intent(FirstActivity.this,SecondActivity.class);
iSecond.putExtra("image_path",image_path);
startActivity(iSecond);
In Second Activity onCreate()
Bundle extras = intent.getExtras();
if(extras != null)
String image_path = extras.getString("image_path");
From this image path , You can get image and set to imageview
ImageView iv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
iv = (ImageView) findViewById(R.id.imageView1);
File imgFile = new File("/storage/emulated/0/1426484497.png");
if (imgFile.exists()) {
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile
.getAbsolutePath());
iv.setImageBitmap(myBitmap);
}
}
You can do this by adding a ImageView to your Activity.
A simple ImageView should look like this:
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageView" />
Then you capture it in your Activity class
ImageView imageView = (ImageView) this.findViewById(R.id.imageView);
Now the fun part. We'll capture your image using the image URI and parse it in a bitmap.
Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath()); //Here goes your image path
imageView.setImageBitmap(Bitmap.createScaledBitmap(bitmap,imageView.getWidth(), imageView.getHeight(), false)); //I scale the bitmap so it show properly. If the image is too big, it wont show on the ImageView
That should do the trick, tell me if it works!

Bitmap to File, Not showing in Default Gallery App

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

How do I save my imageView image into Gallery (Android Development)

I am trying to create an onClick event to save an imageview into the phone Gallery by the click of a Button, below is my code. it does not save into the Gallery, can anyone help me figure out why?
sharebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View b) {
// TODO Auto-generated method stub
//attempt to save the image
b = findViewById(R.id.imageView);
b.setDrawingCacheEnabled(true);
Bitmap bitmap = b.getDrawingCache();
//File file = new File("/DCIM/Camera/image.jpg");
File root = Environment.getExternalStorageDirectory();
File cachePath = new File(root.getAbsolutePath() + "/DCIM/Camera/image.jpg");
try
{
cachePath.createNewFile();
FileOutputStream ostream = new FileOutputStream(cachePath);
bitmap.compress(CompressFormat.JPEG, 100, ostream);
ostream.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
});
I do this to save Image in gallery.
private void saveImageToGallery(){
imageview.setDrawingCacheEnabled(true);
Bitmap b = imageview.getDrawingCache();
Images.Media.insertImage(getActivity().getContentResolver(), b,title, description);
}
insertImage() will return a String != null if image has been really saved.
Also: Needs permission in the manifest as "android.permission.WRITE_EXTERNAL_STORAGE"
And note that this puts the image at the bottom of the list of images already in the gallery.
Hope this helps.
Suppose the ImageView already keeps the image that you want to save, first, get the Bitmap
imageView.buildDrawingCache();
Bitmap bm=imageView.getDrawingCache();
Then save it with below code:-
MediaStore.Images.Media.insertImage(getContentResolver(), yourBitmap, yourTitle , yourDescription);
And do not forget to set this permission in your manifest:-
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
You have to save the image to media provider. Here is a simple example:
Uri saveMediaEntry(String imagePath,String title,String description,long dateTaken,int orientation,Location loc) {
ContentValues v = new ContentValues();
v.put(Images.Media.TITLE, title);
v.put(Images.Media.DISPLAY_NAME, displayName);
v.put(Images.Media.DESCRIPTION, description);
v.put(Images.Media.DATE_ADDED, dateTaken);
v.put(Images.Media.DATE_TAKEN, dateTaken);
v.put(Images.Media.DATE_MODIFIED, dateTaken) ;
v.put(Images.Media.MIME_TYPE, “image/jpeg”);
v.put(Images.Media.ORIENTATION, orientation);
File f = new File(imagePath) ;
File parent = f.getParentFile() ;
String path = parent.toString().toLowerCase() ;
String name = parent.getName().toLowerCase() ;
v.put(Images.ImageColumns.BUCKET_ID, path.hashCode());
v.put(Images.ImageColumns.BUCKET_DISPLAY_NAME, name);
v.put(Images.Media.SIZE,f.length()) ;
f = null ;
if( targ_loc != null ) {
v.put(Images.Media.LATITUDE, loc.getLatitude());
v.put(Images.Media.LONGITUDE, loc.getLongitude());
}
v.put(“_data”,imagePath) ;
ContentResolver c = getContentResolver() ;
return c.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, v);
}
public static void addImageToGallery(final String filePath, final Context context) {
ContentValues values = new ContentValues();
values.put(Images.Media.DATE_TAKEN, System.currentTimeMillis());
values.put(Images.Media.MIME_TYPE, "image/jpeg");
values.put(MediaStore.MediaColumns.DATA, filePath);
context.getContentResolver().insert(Images.Media.EXTERNAL_CONTENT_URI, values);
}
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);
}
Check this out: http://developer.android.com/training/camera/photobasics.html#TaskGallery

Categories

Resources