How do I save the imageview created to camera roll? - android

In the code below, you can see that I have created an imageview using a bitmap. What I want to know is how I can save an image of that imageview to my camera roll. Thanks!
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.key_code_zoom);
title = (TextView) findViewById(R.id.accountTitleLarge);
imageView = (ImageView) findViewById(R.id.keyCodeLarge);
Intent callingActivity = getIntent();
Bundle callingBundle = callingActivity.getExtras();
if (callingBundle != null) {
String titleText = callingBundle.getString("title");
byte[] bytes = getIntent().getByteArrayExtra("bitmapbytes");
bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
title.setText(titleText);
imageView.setImageBitmap(bmp);
}
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
supportFinishAfterTransition();
}
});
}

To save an image in gallery, you must first get the bitmap and then save it.
private void imageToRoll(){
imageView.buildDrawingCache();
Bitmap image = imageView.getDrawingCache(); // Gets the Bitmap
MediaStore.Images.Media.insertImage(getContentResolver(), imageBitmap, imagTitle , imageDescription); // Saves the image.
}
Also, set the permission in your manifest.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

If you are looking for some code that will help you save the Image from the ImageView to your phone storage then the following code will help you
public String getImageFromView() {
imageview.setDrawingCacheEnabled(true);
// this is the important code :)
// Without it the view will have a dimension of 0,0 and the bitmap will be null
imageview.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
imageview.layout(0, 0, imageview.getMeasuredWidth(), imageview.getMeasuredHeight());
imageview.buildDrawingCache(true);
//Define a bitmap with the same size as the view
Bitmap b = imageview.getDrawingCache();
String imgPath = getImageFilename();
File file = new File(imgPath);
try {
OutputStream os = new FileOutputStream(file);
b.compress(Bitmap.CompressFormat.JPEG, 90, os);
os.flush();
os.close();
ContentValues image = new ContentValues();
image.put(Images.Media.TITLE, "NST");
image.put(Images.Media.DISPLAY_NAME, imgPath.substring(imgPath.lastIndexOf('/')+1));
image.put(Images.Media.DESCRIPTION, "App Image");
image.put(Images.Media.DATE_ADDED, System.currentTimeMillis());
image.put(Images.Media.MIME_TYPE, "image/jpg");
image.put(Images.Media.ORIENTATION, 0);
File parent = file.getParentFile();
image.put(Images.ImageColumns.BUCKET_ID, parent.toString()
.toLowerCase().hashCode());
image.put(Images.ImageColumns.BUCKET_DISPLAY_NAME, parent.getName()
.toLowerCase());
image.put(Images.Media.SIZE, file.length());
image.put(Images.Media.DATA, file.getAbsolutePath());
Uri result = mContext.getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, image);
} catch (FileNotFoundException fnfe) {
fnfe.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return imgPath;
}
you will have to provide a file path getImageFilename();this function provides the path where the file is suppose to be stored. The ContentValues will be responsible to let the images be scanned in gallery.
Hope this helps.

Related

Share loaded image with glide from imageview

I have a loaded image on my imageview widget which was loaded from glide library. I want to use a share intent to share that image to other applications. I have tried various possibilities without any success. Please help.
public class BookstorePreviewActivity extends AppCompatActivity {
ImageView imageView;
LinearLayout mShare;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bookstore_preview);
imageView = findViewById(R.id.image_preview_books);
mShare= findViewById(R.id.download_books);
mShare.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// fetching image view item from cache
imageView.setDrawingCacheEnabled(true);
Bitmap bitmap = imageView.getDrawingCache();
File root = Environment.getExternalStorageDirectory();
File cachePath = new File(root.getAbsolutePath());
try {
cachePath.createNewFile();
FileOutputStream outputStream = new FileOutputStream(cachePath);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
// sharing image to other applications (image not found)
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/*");
share.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(cachePath));
startActivity(Intent.createChooser(share, "Share via"));
}
});
Just Pass activity context to the takeScreenShot activity it will
work!!!
public static Bitmap takeScreenShot(Activity activity) {
View view = activity.getWindow().getDecorView();
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
Bitmap b1 = view.getDrawingCache();
Rect frame = new Rect();
activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
int statusBarHeight = frame.top;
//Find the screen dimensions to create bitmap in the same size.
DisplayMetrics dm = activity.getResources().getDisplayMetrics();
int width = dm.widthPixels;
int height = dm.heightPixels;
Bitmap b = Bitmap.createBitmap(b1, 0, statusBarHeight, width, height - statusBarHeight);
view.destroyDrawingCache();
takeScreen(b,activity);
return b;
}
public static void takeScreen(Bitmap bitmap,Activity a) {
//Bitmap bitmap = ImageUtils.loadBitmapFromView(this, view); //get Bitmap from the view
String mPath = Environment.getExternalStorageDirectory() + File.separator + "tarunkonda" + System.currentTimeMillis() + ".jpeg";
File imageFile = new File(mPath);
try {
OutputStream fout = new FileOutputStream(imageFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fout);
fout.flush();
fout.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
openScreenshot(imageFile,a);
}
private static void openScreenshot(File imageFile,Activity activity) {
Intent intent = new Intent(activity,ImageDrawActivity.class);
intent.putExtra(ScreenShotActivity.PATH_INTENT_KEY,imageFile.getAbsolutePath());
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
activity.startActivity(intent);
}

How to save the image?

I am using Picasso to fetch image and I just want to save the image.Below code is not working for me to save the image.
public class DownloadImage extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mindmaps);
final ImageView imageView = (ImageView) findViewById(R.id.imageView);
Picasso.with(this)
.load("http://i.imgur.com/DvpvklR.png")
.into(imageView);
final Button btntakephoto = (Button) findViewById(R.id.save);
btntakephoto.setOnClickListener((View.OnClickListener) this);
}
public void onClick(View v){
ImageView imageView = (ImageView) findViewById(R.id.imageView);
Drawable image = imageView.getDrawable();
if (image != null && image instanceof BitmapDrawable) {
BitmapDrawable drawable = (BitmapDrawable) image;
Bitmap bitmap = drawable.getBitmap();
try {
File file = new File("path where you want to save");
FileOutputStream stream = new FileOutputStream(file);
bitmap.compress(CompressFormat.PNG, 100, stream);
stream.flush();
stream.close();
} catch (Exception e) {
// TODO: handle exception
}
}
}
On pressing the save button image should be saved in the gallery.
MediaStore.Images.Media.insertImage(getContentResolver(), yourBitmap, yourTitle , yourDescription);
try this,
call this method from button click:
private void saveImage() {
ImageView imageView = (ImageView) findViewById(R.id.imageView);
Drawable image = imageView.getDrawable();
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), image);
OutputStream out = null;
String fileName = "MyImage.jpg";
String mPath = "";
try {
out = mActivity.openFileOutput(fileName, Context.MODE_PRIVATE);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
File f = mActivity.getFileStreamPath(fileName);
mPath = f.getAbsolutePath();
} catch (Exception e) {
e.printStackTrace();
}
Logger.logger("URI :" + mPath);
}
Make your DownloadImage class implement View.OnClickListener interface.

how to covert image view into bitmap in android studio?

Can anyone tell me how to convert imageview to bitmap? In my app, i'm accessing the gallery and getting a bitmap of a picture into an imageview, then using picasso, i'm resizing the images that are too big to directly uploaded to parse. I can resize the image in the image view using picasso but how do i get the bitmap from the image view to upload to parse? this is my code..
public static final int IMAGE_GALLERY_REQUEST = 20;
private ImageView imgPicture;
public Bitmap image;
public void openGallery(View view){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);//
startActivityForResult(Intent.createChooser(intent, "Select Picture"),IMAGE_GALLERY_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
// if we are here, everything processed successfully.
if (requestCode == IMAGE_GALLERY_REQUEST) {
Uri imageUri = data.getData();
InputStream inputStream;
try {
inputStream = getContentResolver().openInputStream(imageUri);
image = BitmapFactory.decodeStream(inputStream);
height= image.getHeight();
h= String.valueOf(height);
width= image.getWidth();
w= String.valueOf(width);
if (width>800 || height>600)
{
Picasso.with(this)
.load(imageUri)
.resize(800,600)
.centerCrop()
.into(imgPicture);
// imgPicture.setImageBitmap(image);
//what should i write here to convert this imageview to bitmap? and then later use that bitmap to upload the image to parse?
}
else
{
//do nothing
imgPicture.setImageBitmap(image);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
// show a message to the user indictating that the image is unavailable.
Toast.makeText(this, "Unable to open image", Toast.LENGTH_LONG).show();
}
}
}
}
You only can generate the bitmap from imageview but not in real image size, this generate the bitmap with imageview size
Bitmap bitmap;
try {
bitmap = Bitmap.createBitmap(YOUR_VIEW.getWidth(), YOUR_VIEW.getHeight(),
Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
YOUR_VIEW.draw(canvas);
File root = Environment.getExternalStoragePublicDirectory(Environment.PICTURES);
String fname = "NAME_OF_FILE.jpg";
file = new File(root, fname);
try {
if (!root.exists()) {
root.mkdir();
}
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
YOUR_VIEW.destroyDrawingCache();
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
}
If you don't wanna save to a file, use this code:
public static Bitmap getScreenViewBitmap(View v) {
v.setDrawingCacheEnabled(true);
// this is the important code :)
// Without it the view will have a dimension of 0,0 and the bitmap will be null
v.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
v.layout(0, 0, v.getMeasuredWidth(), v.getMeasuredHeight());
v.buildDrawingCache(true);
Bitmap b = Bitmap.createBitmap(v.getDrawingCache());
v.setDrawingCacheEnabled(false); // clear drawing cache
return b;
}

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

Android:Problem in getting image from specified path

I have an app from which i have to capture an image from camera activity and using content resolver i have insert that image to media.EXTERNAL_CONTENT_URI and i have getString() the path of that image and passed it to bundle in other activity.
from there,I have get that path and put it in Bitmap bitmap = BitmapFactory.decodeFile(filepath);
but it's showing FILENOTFOUNDEXCEPTION and NULLPOINTEREXCEPTION.How to resolve that?
so I am also trying another approach such that the image i got in first activity should first be set to a file and then i decode that file easily?
please suggest me the way to do that.
UPDATES-->
CODE: `//pass image path to other activity`
case PICK_FROM_CAMERA : if (resultCode == RESULT_OK)
{
ContentValues values = new ContentValues();
values.put(Images.Media.TITLE, "title");
values.put(Images.Media.BUCKET_ID, "test");
values.put(Images.Media.DESCRIPTION, "test Image taken");
values.put(Images.Media.MIME_TYPE,"image/jpeg");
Uri uri = getContentResolver().insert(Media.EXTERNAL_CONTENT_URI, values);
filepath = uri.getPath();
Bitmap photo = (Bitmap) data.getExtras().get("data");
//((ImageView)findViewById(R.id.selectedimage)).setImageBitmap(photo);
OutputStream outstream;
try
{
outstream = getContentResolver().openOutputStream(uri);
photo.compress(Bitmap.CompressFormat.JPEG,100,outstream);
outstream.close();
}
catch (FileNotFoundException e) {}
catch (IOException e) {}
Intent intent = new Intent(this.getApplicationContext(),AnimationActivity.class);
Bundle bundle = new Bundle();
bundle.putInt("flag", 0);
bundle.putString("filepath", filepath);
intent.putExtras(bundle);
startActivity(intent);
}
Code: //show that image
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ImageView img = (ImageView)findViewById(R.id.background);
Bitmap border = BitmapFactory.decodeResource(getResources(),R.drawable.border1);
Bundle extra = getIntent().getExtras();
mfilepath = extra.getString("filepath");
int flag = extra.getInt("flag");
if(flag==1)
{
bgr= BitmapFactory.decodeFile(mfilepath);
}
if(flag==0)
{
bgr=BitmapFactory.decodeFile(mfilepath);
OutputStream outstream;
try
{
outstream = getContentResolver().openOutputStream(Uri.fromFile(new File(mfilepath)));
//bgr.compress(Bitmap.CompressFormat.JPEG,100,outstream);
outstream.close();
}
catch (FileNotFoundException e) {}
catch (IOException e) {}
}
bmOverlay = Bitmap.createBitmap(border.getWidth(),border.getHeight(),bgr.getConfig());
canvas = new Canvas(bmOverlay);
canvas.drawBitmap(bmOverlay, 0, 0, null);
canvas.drawBitmap(bgr, 0, 0, null);
canvas.drawBitmap(border,0,0, null);
canvas.save();
img.setImageBitmap(bmOverlay);
Try this simple method, I think it should solve your problem.
private void savePicture(String filename, Bitmap b, Context ctx) {
try {
FileOutputStream out;
out = ctx.openFileOutput(filename, Context.MODE_WORLD_READABLE);
b.compress(Bitmap.CompressFormat.JPEG, 40, out);
if (b.compress(Bitmap.CompressFormat.JPEG, 40, out) == true)
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Edit 1: Although I am not sure exactly what you are asking, I think you might be looking for this method:
private void takePicture() {
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
File photo = new File(Environment.getExternalStorageDirectory(),
"Pic.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo));
imageUri = Uri.fromFile(photo);
startActivityForResult(intent, 0);
}
Use of FileOutputStream instead of OutputStream solved ma problem.
case PICK_FROM_CAMERA : if (resultCode == RESULT_OK)
{
ContentValues values = new ContentValues();
values.put(Images.Media.TITLE, "title");
values.put(Images.Media.BUCKET_ID, "test");
values.put(Images.Media.DESCRIPTION, "test Image taken");
values.put(Images.Media.MIME_TYPE,"image/jpeg");
Uri uri = getContentResolver().insert(Media.EXTERNAL_CONTENT_URI, values);
filepath = uri.getPath();
Bitmap photo = (Bitmap) data.getExtras().get("data");
try
{
FileOutputStream outstream; =new FileOutputStream(filepath);
photo.compress(Bitmap.CompressFormat.JPEG,100,outstream);
outstream.close();
}
catch (FileNotFoundException e) {}
catch (IOException e) {}
Intent intent = new Intent(this.getApplicationContext(),AnimationActivity.class);
Bundle bundle = new Bundle();
bundle.putInt("flag", 0);
bundle.putString("filepath", filepath);
intent.putExtras(bundle);
startActivity(intent);
}
Code: //show that image
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ImageView img = (ImageView)findViewById(R.id.background);
Bitmap border = BitmapFactory.decodeResource(getResources(),R.drawable.border1);
Bundle extra = getIntent().getExtras();
mfilepath = extra.getString("filepath");
bgr= BitmapFactory.decodeFile(mfilepath);
bmOverlay = Bitmap.createBitmap(border.getWidth(),border.getHeight(),bgr.getConfig());
canvas = new Canvas(bmOverlay);
canvas.drawBitmap(bmOverlay, 0, 0, null);
canvas.drawBitmap(bgr, 0, 0, null);
canvas.drawBitmap(border,0,0, null);
canvas.save();
img.setImageBitmap(bmOverlay);

Categories

Resources