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);
Related
I would like to share a screenshot after user clicking "share" button.
I am trying to apply this solution: https://stackoverflow.com/a/30212385/9748825
Here are the three methods:
public static Bitmap getScreenShot(View view) {
View screenView = view.getRootView();
screenView.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(screenView.getDrawingCache());
screenView.setDrawingCacheEnabled(false);
return bitmap;
}
public void store(Bitmap bm, String fileName) {
final String dirPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Screenshots";
File dir = new File(dirPath);
if (!dir.exists())
dir.mkdirs();
File file = new File(dirPath, fileName);
try {
FileOutputStream fOut = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.PNG, 85, fOut);
fOut.flush();
fOut.close();
} catch (Exception e) {
e.printStackTrace();
}
Toast.makeText(this, file.getAbsolutePath(), Toast.LENGTH_SHORT).show();
shareImage(file);
}
public void shareImage(File file) {
Uri uri = FileProvider.getUriForFile(iv_ScoreBoard.this, iv_ScoreBoard.this.getApplicationContext().getPackageName() + ".my.package.name.provider", file);
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND);
intent.setType("image/*");
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.putExtra(android.content.Intent.EXTRA_SUBJECT, "");
intent.putExtra(android.content.Intent.EXTRA_TEXT, "");
intent.putExtra(Intent.EXTRA_STREAM, uri);
try {
startActivity(Intent.createChooser(intent, "Share Screenshot"));
} catch (ActivityNotFoundException e) {
Toast.makeText(iv_ScoreBoard.this, "No App Available", Toast.LENGTH_SHORT).show();
}
}
gameDate method:
public void generateNewGameDate() {
Date thisSecond = Calendar.getInstance().getTime();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd , HH:mm");
gameDate = df.format(thisSecond);
}
Trigger Point:
public void onClick(View v) {
Bitmap b = getScreenShot(rootView);
store(b, gameDate);
}
Error:
java.lang.IllegalArgumentException: Failed to find configured root that contains /storage/emulated/0/Screenshots/2018-10-28 , 17:40
Appreciate any of your help, thanks!
Well I was stuck in external storage permission.
After applying this answer, I got it now. Appreciate stackoverflow so much!
https://stackoverflow.com/a/37672627/9748825
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;
}
btnsave.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mainLayout.setDrawingCacheEnabled(true);
// mainLayout.setDrawingCacheEnabled(true);
Bitmap bitmap =mainLayout.getDrawingCache();
String root = Environment.getExternalStorageDirectory().toString();
File newDir = new File(root + "/saved_images");
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(getApplicationContext(), "saved to your folder", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
} }
});
btnshare.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
mainLayout.setDrawingCacheEnabled(true);
Bitmap bitmap =mainLayout.getDrawingCache();//Getting Complication error here.
// BitmapDrawable bitmapDrawable = (BitmapDrawable)ivdisplayphoto.getDrawable();
// Bitmap bitmap = bitmapDrawable.getBitmap();
//Using above code I am able to share one imageview.
// 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(Intent.ACTION_SEND);
share.setType("image/*");
share.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + sharefile));
try {
startActivity(Intent.createChooser(share, "Share photo"));
} catch (Exception e) {
}
}
});
}
I have 3 ImageViews As imageView1,imageView2,imageView3 and for layout
private RelativeLayout mainLayout;
mainLayout= (RelativeLayout) findViewById(R.id.childLayout);
Bitmap bitmap =mainLayout.getDrawingCache();
Only this was missing.
Now my code is working fine.
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
I have following method to Capture Screen on Action Item Click. Its working on Android <2.3 but not on 4+. What is wrong with this way of screen capture.
private void captureScreen() {
View v = mapView.getRootView();
v.setDrawingCacheEnabled(true);
Bitmap capturedBitmap = Bitmap.createBitmap(v.getDrawingCache());
v.setDrawingCacheEnabled(false);
if(capturedBitmap != null) {
Intent intent = new Intent(this, ScreenCapturedAlertActivity.class);
intent.putExtra("capturedImage", capturedBitmap);
intent.putExtra("name", location.getName());
startActivity(intent);
} else {
Toast.makeText(this, "Screen Capture Failed", Toast.LENGTH_SHORT).show();
}
}
The ScreenCaputureAlertActivity.java >>>
public class ScreenCapturedAlertActivity extends SherlockActivity {
private ImageView capturedImage;
private Bitmap capturedBitmap;
private String name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_screencaptured_alert);
capturedBitmap = (Bitmap) getIntent().getParcelableExtra("capturedImage");
name = getIntent().getStringExtra("name");
capturedImage = (ImageView) findViewById(R.id.ivCapturedImage);
capturedImage.setImageBitmap(capturedBitmap);
}
private void saveAndShare(boolean share) {
String root = Environment.getExternalStorageDirectory().toString();
File dir = new File(root + "/capture/");
if(!dir.exists())
dir.mkdirs();
FileOutputStream outStream = null;
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
File file = new File(dir, "Capture "+n+".jpg");
if(file.exists()) {
file.delete();
}
try {
outStream = new FileOutputStream(file);
capturedBitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
outStream.flush();
outStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
Toast.makeText(this, "Save Failed", Toast.LENGTH_SHORT).show();
return;
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(this, "Save Failed", Toast.LENGTH_SHORT).show();
return;
}
if(share) {
Uri screenshotUri = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(Intent.EXTRA_STREAM, screenshotUri);
intent.putExtra(Intent.EXTRA_SUBJECT, "Location of " + name);
intent.putExtra(Intent.EXTRA_TITLE, getText(R.string.screen_share_message));
intent.putExtra(Intent.EXTRA_TEXT, getText(R.string.screen_share_message));
intent.setType("image/*");
startActivity(Intent.createChooser(intent, "Share with"));
finish();
} else {
Toast.makeText(this, "Save Success", Toast.LENGTH_SHORT).show();
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,Uri.parse("file://" + Environment.getExternalStorageDirectory())));
finish();
}
}
public void saveCapture(View view) {
saveAndShare(false);
}
public void shareCapture(View view) {
saveAndShare(true);
}
}
Thanks to #KumarBibek guidance.
The error I was getting was
!!! FAILED BINDER TRANSACTION !!!
So as from the selected answer from the link
Send Bitmap as Byte Array
I did like this in first activity:
private void captureScreen() {
View v = mapView.getRootView();
v.setDrawingCacheEnabled(true);
Bitmap capturedBitmap = Bitmap.createBitmap(v.getDrawingCache());
v.setDrawingCacheEnabled(false);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
capturedBitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
if(capturedBitmap != null) {
Intent intent = new Intent(this, ScreenCapturedAlertActivity.class);
intent.putExtra("capture", byteArray);
intent.putExtra("name", location.getName());
startActivity(intent);
} else {
Toast.makeText(this, "Screen Capture Failed", Toast.LENGTH_SHORT).show();
}
}
And in ScreenCapturedAlertActivity :
byte[] byteArray = getIntent().getByteArrayExtra("capture");
capturedBitmap = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
It is working WELL now. Thanks again to #KumarBibek
Instead of passing the whole bitmap, try passing the file saved file's path to the next activity. Bitmap is a large object, and it's not supposed to be passed around like that.
Since you already checked the the image is being saved fine, if you deal with paths instead of bitmaps, I think it would solve your problem.