I am using share intent in my application,but i am not able to share image and text,i am using image and text from my json response,but it is not working.i am not getting any error,but the the method for sharing is not working
JSON Response : http://pastie.org/10753346
public void onShareItem(View v) {
// Get access to bitmap image from view
// Get access to the URI for the bitmap
Uri bmpUri = getLocalBitmapUri(descpic);
if (bmpUri != null) {
// Construct a ShareIntent with link to image
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, bmpUri);
shareIntent.putExtra(Intent.EXTRA_TEXT, desc.getText().toString());
shareIntent.setType("image/*");
// Launch sharing dialog for image
startActivity(Intent.createChooser(shareIntent, "Share Image"));
} else {
// ...sharing failed, handle error
}
}
// Returns the URI path to the Bitmap displayed in specified ImageView
public Uri getLocalBitmapUri(ImageView imageView) {
// Extract Bitmap from ImageView drawable
Drawable drawable = imageView.getDrawable();
Bitmap bmp = null;
if (drawable instanceof BitmapDrawable){
bmp = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
} else {
return null;
}
// Store image to default external storage directory
/*Uri bmpUri = null;
try {
File file = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS), "share_image_" + System.currentTimeMillis() + ".png");
file.getParentFile().mkdirs();
FileOutputStream out = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.PNG, 90, out);
out.close();
bmpUri = Uri.fromFile(file);
} catch (IOException e) {
e.printStackTrace();
}*/
OutputStream fOut = null;
Uri outputFileUri=null;
try {
File root = new File(Environment.getExternalStorageDirectory()
+ File.separator + "folder_name" + File.separator);
root.mkdirs();
File sdImageMainDirectory = new File(root, "myPicName.jpg");
outputFileUri = Uri.fromFile(sdImageMainDirectory);
fOut = new FileOutputStream(sdImageMainDirectory);
} catch (Exception e) {
Toast.makeText(this, "Error occured. Please try again later.",
Toast.LENGTH_SHORT).show();
}
try {
bmp.compress(Bitmap.CompressFormat.PNG, 100, fOut);
fOut.flush();
fOut.close();
} catch (Exception e) {
}
return outputFileUri;
}
Do this to save image. Replace your method with this
public Uri getLocalBitmapUri(ImageView imageView) {
imageview.buildDrawingCache();
Bitmap bm = imageview.getDrawingCache();
OutputStream fOut = null;
Uri outputFileUri;
try {
File root = new File(Environment.getExternalStorageDirectory()
+ File.separator + "folder_name" + File.separator);
root.mkdirs();
File imageFile = new File(root, "myPicName.jpg");
outputFileUri = Uri.fromFile(imageFile);
fOut = new FileOutputStream(imageFile);
} catch (Exception e) {
e.printStackTrace();
}
try {
bm.compress(Bitmap.CompressFormat.PNG, 100, fOut);
fOut.flush();
fOut.close();
return outputFileUri;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
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 :-)
Here i am making drawable view into bitmap.
mDrawingPad.setVisibility(View.VISIBLE);
BitmapDrawable ob = new BitmapDrawable(getResources(),
bitmapconv);
DrawingView mDrawingView=new
DrawingView(Previewimage.this);
mDrawingPad.addView(mDrawingView);
mDrawingView.setBackground(ob);
mDrawingView.buildDrawingCache();
drawbitmap=mDrawingView.getDrawingCache();
I need to convert this into URI to send to image cropper library
CropImage.activity(uri).start(Previewimage.this);
/*This saveImage method will return String path*/
path = saveImage();
Uri uri = Uri.parse(path);
/****************************************************/
private String saveImage()
{
Bitmap bitmap;
mDrawingView.setDrawingCacheEnabled(true);
mDrawingView.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
mDrawingView.buildDrawingCache();
bitmap = Bitmap.createBitmap(mDrawingView.getDrawingCache());
String state = Environment.getExternalStorageState();
String root = "";
String fileName = "/MyImage" + System.currentTimeMillis() + "Image"+ ".jpg";
String parent = "App_Name";
File mFile;
if (Environment.MEDIA_MOUNTED.equals(state)) {
root = Environment.getExternalStorageDirectory().toString();
mFile = new File(root, parent);
if (!mFile.isDirectory())
mFile.mkdirs();
} else {
root = FriendsImageSending.this.getFilesDir().toString();
mFile = new File(root, parent);
if (!mFile.isDirectory())
mFile.mkdirs();
}
String strCaptured_FileName = root + "/App_Name" + fileName;
File f = new File(strCaptured_FileName);
try {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 95, bytes);
FileOutputStream fo;
fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
fo.close();
bitmap.recycle();
System.gc();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return strCaptured_FileName;
}
This part of code works:
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
your_bitmap_image.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(your_context.getContentResolver(), your_bitmap_image, "your_title", null);
Uri uri = Uri.parse(path);
just try to replace the areas that I mentioned in it
in the place of "your_context" if you are in an activity put this:
MediaStore.Images.Media.insertImage(getContentResolver(), your_bitmap_image, "your_title", null);
Uri uri = Uri.parse(path);
if you are in a fragment :
MediaStore.Images.Media.insertImage(getContext().getContentResolver(), your_bitmap_image, "your_title", null);
Uri uri = Uri.parse(path);
Use this method:
public Uri getImageUri(Context ctx, Bitmap bitmap) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = Images.Media.insertImage(ctx.getContentResolver(),
bitmap, "Temp", null);
return Uri.parse(path);
}
If you are calling this method inside an Activity then call this method like this:
getImageUri(YourClassName.this, yourbitmap);
But if you are calling this in an Fragment then call like this:
getImageUri(getActivity(), yourbitmap);
My old code was only working well till lolipop. i tried to write a new one but its not working in marshmallow either. I been sitting on this for the last two days and i dont have a clue :(.
public void share(View view){
niv1 = (NetworkImageView) findViewById(R.id.imgNetwork);
File file = getLocalBitmapFile(niv1);
Uri bmpUrii = FileProvider.getUriForFile(this, "com.myfileprovider", file);
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("image/*");
shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
shareIntent.putExtra(Intent.EXTRA_STREAM, bmpUrii);
shareIntent.putExtra(Intent.EXTRA_SUBJECT, "share");
shareIntent.putExtra(Intent.EXTRA_TEXT, Datas.Address);
startActivity(Intent.createChooser(shareIntent, "Share Image"));
}
public File getLocalBitmapFile(NetworkImageView imageView) {
Drawable drawable = imageView.getDrawable();
Bitmap bmp = null;
if (drawable instanceof BitmapDrawable) {
bmp = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
} else {
return null;
}
File bmpUri = null;
File file = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS), "share_image_" + System.currentTimeMillis() + ".png");
file.getParentFile().mkdirs();
FileOutputStream out = null;
try {
out = new FileOutputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
bmp.compress(Bitmap.CompressFormat.PNG, 90, out);
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
return file;
}
I am using a picture to display from web service.Now how to use image to set as profile picture of whatsapp or any other profile picture option. I am able to save and share an image. But how to provide an option in menu or as button to set picture as->
Similar to this which is used in Gallery..
I used for save and share button for image but don't know how to implement set profile photo.
share.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
BitmapDrawable bitmapDrawable = (BitmapDrawable)image.getDrawable();
Bitmap bitmap = bitmapDrawable.getBitmap();
// Save this bitmap to a file.
File cache = activity.getExternalCacheDir();
File sharefile = new File(cache, "save.png"); //give your name and save it.
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));
try {
activity.startActivity(Intent.createChooser(share, "Share photo"));
} catch (Exception e) {
}
}
});
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
image.setDrawingCacheEnabled(true);
Bitmap bitmap = image.getDrawingCache();
String root = Environment.getExternalStorageDirectory().toString();
File newDir = new File(root + "/Nokia");
newDir.mkdirs();
Random gen = new Random();
int n = 10000;
n = gen.nextInt(n);
String fotoname = "Photo-"+ n +".jpg";
File file = new File (newDir, fotoname);
if (file.exists ()) file.delete ();
try {
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
Toast.makeText(activity, "Saved to your folder"+fotoname, Toast.LENGTH_SHORT ).show();
} catch (Exception e) {
}
}
});
On button Click :
OnButtonClick(){
ImageProcessing imageProcessing = new ImageProcessing();
Bitmap bitmap = imageProcessing.takeScreenshot(getWindow().getDecorView().findViewById(R.id.view_thought));
imageProcessing.saveBitmap(bitmap);
Intent intent = imageProcessing.setAsOption(this,imageProcessing.getSavedImagePath());
startActivityForResult(Intent.createChooser(intent, "Set image as"), 200);
}
Implement a new class ImageProcessing
public class ImageProcessing {
private File imagesPath;
public void saveBitmap(Bitmap bitmap) {
imagesPath = new File(Environment.getExternalStorageDirectory() + "/screenshot.jpg");
FileOutputStream fos;
try {
fos = new FileOutputStream(imagesPath);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
Log.e("POS", e.getMessage(), e);
} catch (IOException e) {
Log.e("POS", e.getMessage(), e);
}
}
public File getSavedImagePath(){
imagesPath = new File(Environment.getExternalStorageDirectory() + "/screenshot.jpg");
return imagesPath;
}
public Bitmap takeScreenshot(View rootView) {
rootView.setDrawingCacheEnabled(true);
return rootView.getDrawingCache();
}
public Intent setAsOption(Context cntxt,File imagesPath){
/*File imagesPath = new File(Environment.getExternalStorageDirectory() + "/screenshot.jpg");*/
Intent intent = new Intent(Intent.ACTION_ATTACH_DATA);
if(imagesPath.exists()){
Uri contentUri = FileProvider.getUriForFile(cntxt, BuildConfig.APPLICATION_ID+".Utility.GenericFileProvider",imagesPath);
intent.setDataAndType(contentUri, "image/jpg");
intent.putExtra("mimeType", "image/jpg");
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
}else {
Toast.makeText(cntxt,"Not a wallpaper",Toast.LENGTH_SHORT).show();
}
return intent;
}
}
In menifest add :
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.SET_WALLPAPER" />
Intent intent = new Intent(Intent.ACTION_ATTACH_DATA);
intent.setDataAndType(Uri.parse("file:///" + yourFile), "image/jpg");
intent.putExtra("mimeType", "image/jpg");
startActivityForResult(Intent.createChooser(intent, "Set As"), 200);
testButton.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View v)
{
imageView.setImageBitmap(Bitmap);
imageView.buildDrawingCache();
Bitmap bm =imageView.getDrawingCache();
Intent imageIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
File imagesFolder = new File(Environment.getExternalStorageDirectory(), "Punch");
imagesFolder.mkdirs();
String fileName = "image" + ".jpg";
File output = new File(imagesFolder, fileName);
Uri uriSavedImage = Uri.fromFile(output);
imageIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
OutputStream fos = null;
try {
fos = getContentResolver().openOutputStream(uriSavedImage);
bm.compress(CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{}
}
});
First i retrieved an image from sd card to image view of resolution (640 x 480). Then again i saved the image from image view to sd card. But the image saved is of resolution is (188x113). Can anyone suggest how i can save with the same resolution. Any suggestions will be appreciable.
Try this code :
BitmapDrawable btmpDr = (BitmapDrawable) ivPic.getDrawable();
Bitmap bmp = btmpDr.getBitmap();
/*File sdCardDirectory = Environment.getExternalStorageDirectory();*/
try
{
File sdCardDirectory = new File(Environment.getExternalStorageDirectory() + File.separator + "MeeguImages");
sdCardDirectory.mkdirs();
imageNameForSDCard = "image_" + String.valueOf(random.nextInt(1000)) + System.currentTimeMillis() + ".jpg";
File image = new File(sdCardDirectory, imageNameForSDCard);
FileOutputStream outStream;
outStream = new FileOutputStream(image);
bmp.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
/* 100 to keep full quality of the image */
outStream.flush();
outStream.close();
//Refreshing SD card
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"+ Environment.getExternalStorageDirectory())));
}
catch (Exception e)
{
e.printStackTrace();
Toast.makeText(ViewImage.this, "Image could not be saved : Please ensure you have SD card installed " +
"properly", Toast.LENGTH_LONG).show();
}
bm.compress(CompressFormat.JPEG, 100, fos);
remove this line
Solved, This is how i achieved to save image from ImageView
/*Variable which holds Image*/
{ImageView ivBanner = "Initialise It :)";
FileOutputStream fileOutputStream = openFileOutput("ImageName" + ".jpg", MODE_PRIVATE);
Bitmap bitmap = convertToBitMap(ivBanner.getDrawable(),ivBanner.getWidth(),ivBanner.getHeight());
bitmap.compress(Bitmap.CompressFormat.JPEG, 85, fileOutputStream);
File file = getFileStreamPath("ImageName" + ".jpg");
File f = file.getAbsoluteFile();
/*Utilise your path whatever way you want*/
String localPath = f.getAbsolutePath();}
/* Covert Drawable to Bitmap*/
private Bitmap convertToBitMap(Drawable drawable, int width, int height) {
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0,0,width,height);
drawable.draw(canvas);
return bitmap;
}