How to implement snapshot in google map in android - android

I am new to Android App development. And I want to implement the snapshot in the google map triggered by the info window on the map, then I need to return the image and crop it.
Here is my code, but it doesn't work every time I touch the info window.
Here is the code of snapshot. When I debug it, I found that it jumped over the snapshot method, so I think that maybe my usage of snakshotReadyCallback is wrong.
public void takeSnapShot(){
mMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
//final ImageView snapshotHolder = (ImageView) findViewById(R.id.picture);
final GoogleMap.SnapshotReadyCallback callback = new GoogleMap.SnapshotReadyCallback() {
#Override
public void onSnapshotReady(Bitmap snapshot) {
//snapshotHolder.setImageBitmap(snapshot);
try {
FileOutputStream out = new FileOutputStream("test.png");
snapshot.compress(Bitmap.CompressFormat.PNG, 90, out);
Toast.makeText(MapsActivity.this, "Capture OK", Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
}
}
};
mMap.snapshot(callback);
}
});
}
And here is the code of crop.
//crop the image
public void performCrop(){
try{
Intent cropIntent= new Intent("com.android.camera.action.CROP");
cropIntent.setDataAndType(picUri,"map/*");
cropIntent.putExtra("crop", "true");
cropIntent.putExtra("aspectX", 2);
cropIntent.putExtra("aspectY", 1);
cropIntent.putExtra("outputX", 256);
cropIntent.putExtra("outputY", 256);
cropIntent.putExtra("return-data", true);
startActivityForResult(cropIntent, CROP_PIC);
}catch (ActivityNotFoundException anfe){
Toast.makeText(this, "this device doesn't support crop", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CROP_PIC) {
Bundle extras = data.getExtras();
Bitmap thePic = extras.getParcelable("data");
ImageView picView = (ImageView) findViewById(R.id.picture);
picView.setImageBitmap(thePic);
}
}

Welcome on stackoverflow.
By implementing PlaceAutocompleteFragment and PlaceAutocompleteActivity , you can able to get google place.
See my question and answer which helps you.

Related

startActivityForResults not working when the child activity calls another activity

I have 3 activities say A, B and C.
A calls B.
When B doesn't call C it returns to A. But when B calls C it doesn't return to A, the app stops.
Now the real problem is, from activity A I want to call an image picker and crop the image. That's Activity B which crops and calls C for picking image.
Activity A:
iv_profile_pic.setOnClickListener(new View.OnClickListener() {//iv_profile_pic is an ImageView
#Override
public void onClick(View view) {
Intent i=new Intent(MainActivity.this,profile_pic_chooser.class);
i.setFlags(0);
MainActivity.this.startActivityForResult(i, 999);
Toast.makeText(getApplicationContext(),"Reached",Toast.LENGTH_SHORT).show();
}
});
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == 999) {
Bitmap image=data.getParcelableExtra("picture");
iv_profile_pic.setImageBitmap(image);
}
}
Activity B:
It has 2 buttons. Load and Crop. Load when clicked calls ImageChooserIntent and chooses an image which is opened in B with guidlines to crop.
Crop when clicked should return back to A the cropped image.
If crop is called without calling load, it returns to A with null, of-course.
But if Load is clicked first and then Crop is called, the app simply stops.
public void onLoadImageClick(View view) {
startActivityForResult(getPickImageChooserIntent(), 200);
}
public void onCropImageClick(View view) {
Bitmap cropped = mCropImageView.getCroppedImage(500, 500);
if (cropped != null) {
mCropImageView.setImageBitmap(cropped);
iv.setImageBitmap(cropped);
Intent returnIntent = new Intent();
returnIntent.putExtra("picture", cropped);
setResult(Activity.RESULT_OK, returnIntent);
finish();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
Uri imageUri = getPickImageResultUri(data);
// For API >= 23 we need to check specifically that we have permissions to read external storage,
// but we don't know if we need to for the URI so the simplest is to try open the stream and see if we get error.
boolean requirePermissions = false;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M &&
checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED &&
isUriRequiresPermissions(imageUri)) {
// request permissions and handle the result in onRequestPermissionsResult()
requirePermissions = true;
mCropImageUri = imageUri;
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 0);
}
if (!requirePermissions) {
mCropImageView.setImageUriAsync(imageUri);
}
}
}
I got a workaround. The most probable problem I was facing was:
I was using an external library for cropping the image. This library did 2 things.
First, selected an image using imageChooser intent.
Second, Cropped that image.
After the library cropped the image, it wasn't saving the cropped image in local/external storage. But I was trying to pass it back to parent directory.
There's the problem. The file doesn't exist and still I am trying to use it. The application terminates.
So my workaround was,
• Save the bitmap in storage
• Pass the Uri to parent
• Extract that Uri from child
• Make bitmap from that Uri
• Apply on the ImageView
So Activity B had:
public void onCropImageClick(View view) {
Bitmap cropped = mCropImageView.getCroppedImage(500, 500);
if (cropped != null) {
mCropImageView.setImageBitmap(cropped);
iv.setImageBitmap(cropped);
File externalStorageDirectory = Environment.getExternalStorageDirectory();
externalStorageDirectory= new File(externalStorageDirectory , "FOLDERNAME");
if(!createDirIfNotExists(externalStorageDirectory)){
Toast.makeText(this,"Failed creating Directory!",Toast.LENGTH_SHORT).show();
}else{
File filename=new File(externalStorageDirectory, String.valueOf(Calendar.getInstance().getTimeInMillis())+".PNG");
FileOutputStream out = null;
try {
out = new FileOutputStream(filename);
cropped.compress(Bitmap.CompressFormat.PNG, 100, out); // cropped is your Bitmap instance
// PNG is a lossless format, the compression factor (100) is ignored
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
Intent returnIntent = new Intent();
returnIntent.putExtra("picture", Uri.fromFile(filename));
setResult(RESULT_OK, returnIntent);
finish();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
//Toast.makeText(this,mCropImageUri.toString(),Toast.LENGTH_SHORT).show();
}
And Activity A had:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == 999 && resultCode==RESULT_OK) {
Uri path=data.getParcelableExtra("picture");
Bitmap bitmap=null;
try {
bitmap= MediaStore.Images.Media.getBitmap(this.getContentResolver(), path);
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(this,path.toString(),Toast.LENGTH_SHORT).show();
if (bitmap!=null){
iv_profile_pic.setImageBitmap(bitmap);
}
}
Maybe my problem statement is wrong, but workaround works. Any edits/suggestions
are 100% welcome. Just in-case someone like me gets stuck, this might help!

Capture a custom image size with the camera or crop it

Am working on OCR system which is requiring to capture image and do OCR, i would like to capture part of the paper (Exact where intended text is) or crop captured image before passing it to OCR processing for better results.
I tried bellow code but i can't make it to what am trying to archive as am beginner to android java
private void startCameraActivity() {
try {
String IMGS_PATH = Environment.getExternalStorageDirectory().toString() + "/ocr/imgs";
prepareDirectory(IMGS_PATH);
String img_path = IMGS_PATH + "/ocr.jpg";
outputFileUri = Uri.fromFile(new File(img_path));
final Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
takePictureIntent.putExtra("crop", "true");
takePictureIntent.putExtra("scale", true);
takePictureIntent.putExtra("aspectX", 1);
takePictureIntent.putExtra("aspectY", 1);
takePictureIntent.putExtra("outputX", 150);
takePictureIntent.putExtra("outputY", 100);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, PHOTO_REQUEST_CODE);
}
} catch (Exception e) {
Log.e(TAG, e.getMessage());
}
}
#Override
public void onActivityResult(int requestCode, int resultCode,
Intent data) {
//making photo
if (requestCode == PHOTO_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
doOCR();
} else {
Toast.makeText(this, "ERROR: Image was not obtained.", Toast.LENGTH_SHORT).show();
}
}
private void doOCR() {
prepareTesseract();
startOCR(outputFileUri);
}
Am someone help me out here, Thanks.
NOTE
takePictureIntent.putExtra("crop", "true");
takePictureIntent.putExtra("scale", true);
takePictureIntent.putExtra("aspectX", 1);
takePictureIntent.putExtra("aspectY", 1);
takePictureIntent.putExtra("outputX", 150);
takePictureIntent.putExtra("outputY", 100);
After clearning my cache i noted the above code is opening complete action with apps which can crop image and everything is fine now.
Thanks.

Image cropping is not working in android 7.0 and higher version

I want to capture profile image from camera and crop. In our code camera image is working but cropping is not working.
Camera method
private void cameraIntent() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (intent.resolveActivity(getActivity().getPackageManager()) != null) {
outputFileUri = ProviderUtil.getOutputMediaFileUri(getActivity().getBaseContext());
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(intent, REQUEST_CAMERA);
}
}
Crop Image method
public void cropCapturedImage() {
try {
getActivity().grantUriPermission("com.ht.msb.mysocialbuy.provider",outputFileUri,
Intent.FLAG_GRANT_WRITE_URI_PERMISSION |
Intent.FLAG_GRANT_READ_URI_PERMISSION);
Intent CropIntent = new Intent("com.android.camera.action.CROP");
CropIntent.setDataAndType(outputFileUri, "image/*");
CropIntent.putExtra("crop", "true");
if (imagebrowseType == 1) {
CropIntent.putExtra("outputX", 400);
CropIntent.putExtra("aspectX", 1);
CropIntent.putExtra("aspectY", 1);
} else {
CropIntent.putExtra("outputX", 600);
CropIntent.putExtra("aspectX", 6);
CropIntent.putExtra("aspectY", 4);
}
CropIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
CropIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
CropIntent.putExtra("outputY", 400);
CropIntent.putExtra("scaleUpIfNeeded", true);
CropIntent.putExtra("return-data", true);
CropIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(CropIntent, PIC_CROP);
} catch (ActivityNotFoundException e) {
Log.e("error_crop",e.toString()+" 1");
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == REQUEST_CAMERA) {
if (outputFileUri != null) {
cropCapturedImage();
}
} else if (requestCode == PIC_CROP) {
try {
Bitmap thePic;
if (data != null) {
thePic = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), outputFileUri);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thePic.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
}
} catch (Exception e) {
Log.e("error", e.toString() + "");
}
}
}
}
Android does not have an image-cropping Intent.
You should add a library to your project that handles image cropping, then use that library with the image that you get back from your startActivityForResult() call.
in onActvityResult method change your code like:
if (requestCode == PIC_CROP) {
if (data != null) {
// get the returned data
// get the cropped bitmap
if (data.getExtras()!=null) {
Bundle extras = data.getExtras();
Bitmap selectedBitmap = extras.getParcelable("data");
imgPhoto.setImageBitmap(selectedBitmap);
}
}
}
Or, Use uCrop library which makes things easier.

Capture and Crop Image and save croped Image

I am trying to capture an image and save cropped image instead of original image with specified name.
At the moment I am able to crop and show on imageview but I need to know how to save cropped image instead of original, Here is the code.
final int CAMERA_CAPTURE = 1;
final int CROP_PIC = 2;
private Uri picUri;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button captureBtn = (Button) findViewById(R.id.capture_btn);
captureBtn.setOnClickListener(this);
}
public void onClick(View v) {
if (v.getId() == R.id.capture_btn) {
try {
// use standard intent to capture an image
Intent captureIntent = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
// we will handle the returned data in onActivityResult
startActivityForResult(captureIntent, CAMERA_CAPTURE);
} catch (ActivityNotFoundException anfe) {
Toast toast = Toast.makeText(this, "This device doesn't support the crop action!",
Toast.LENGTH_SHORT);
toast.show();
}
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == CAMERA_CAPTURE) {
// get the Uri for the captured image
picUri = data.getData();
performCrop();
}
// user is returning from cropping the image
else if (requestCode == CROP_PIC) {
// get the returned data
Bundle extras = data.getExtras();
// get the cropped bitmap
Bitmap thePic = extras.getParcelable("data");
ImageView picView = (ImageView) findViewById(R.id.picture);
picView.setImageBitmap(thePic);
}
}
}
/**
* this function does the crop operation.
*/
private void performCrop() {
// take care of exceptions
try {
// call the standard crop action intent (the user device may not
// support it)
Intent cropIntent = new Intent("com.android.camera.action.CROP");
// indicate image type and Uri
cropIntent.setDataAndType(picUri, "image/*");
// set crop properties
cropIntent.putExtra("crop", "true");
// indicate aspect of desired crop
cropIntent.putExtra("aspectX", 2);
cropIntent.putExtra("aspectY", 1);
// indicate output X and Y
cropIntent.putExtra("outputX", 256);
cropIntent.putExtra("outputY", 256);
// retrieve data on return
cropIntent.putExtra("return-data", true);
// start the activity - we handle returning in onActivityResult
startActivityForResult(cropIntent, CROP_PIC);
}
// respond to users whose devices do not support the crop action
catch (ActivityNotFoundException anfe) {
Toast toast = Toast
.makeText(this, "This device doesn't support the crop action!", Toast.LENGTH_SHORT);
toast.show();
}
}
I am new to android and I really want to know how I can do this, any kind of help is much appriciated.
So the question is: How to save a bitmap
Sometimes saving bitmaps takes a long time. I suggest you to use AsyncTask in order to avoid annoying lags in your app.
public class saveFile extends AsyncTask<Void, Void, File>{
#Override
protected void onPreExecute() {
super.onPreExecute();
progressBar.setVisibility(View.VISIBLE);//Show user that app is working in backgrind
}
#Override
protected File doInBackground(Void... params) {
String file_path = Environment.getExternalStorageDirectory().getAbsolutePath() +
"/CropedImage";
File dir = new File(file_path);
if(!dir.exists())
dir.mkdirs();
String format = new SimpleDateFormat("yyyyMMddHHmmss",
java.util.Locale.getDefault()).format(new Date());
File file = new File(dir, format + ".png");
FileOutputStream fOut;
try {
fOut = new FileOutputStream(file);
thePic.compress(Bitmap.CompressFormat.PNG, 100, fOut);
fOut.flush();
fOut.close();
}
catch (Exception e) {
e.printStackTrace();
}
return file;
}
#Override
protected void onPostExecute(File result) {
progressBar.setVisibility(View.INVISIBLE);
String respath=result.getPath().toString();
Toast.makeText(MainActivity.this, "Saved at "+respath, Toast.LENGTH_LONG).show();
MediaScannerConnection.scanFile(MainActivity.this, new String[] { result.getPath() }, new String[] { "image/jpeg" }, null);
}
}
And then call AsyncTask:
new saveFile().execute();
Android does not have any crop intent you can download crop libraries Click here

Android 'set As Wallpaper' functionality

I am developing an application in which I have an image gallery and when I click on any image, it opens in full mode. But I want the set As Wallpaper functionality like android default gallery:
I know it can be done by custom code (setting wallpaper and cropping image). But I want to pass that image to android default wallpaper setter so that android will manage the cropping and setting wallpaper task. How can I do that? How can I pass that image to android default walpaper setter?
You can launch Crop intent by start activity for result and retrieve it in result and then use wallpaper manager class.
like this
Uri imgUri=Uri.parse("android.resource://your.package.name/"+R.drawable.image);
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setDataAndType(imgUri, "image/*");
intent.putExtra("crop", "true");
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("outputX", 80);
intent.putExtra("outputY", 80);
intent.putExtra("return-data", true);
startActivityForResult(intent, REQUEST_CODE_CROP_PHOTO);
and use Wallpaper manager in your onResult function
Also keep in mind that It depends on the device whether that device is support it or not. This Intent action is not part of the internal API. Some manufacturers provide their own Gallery apps and so there is no way of knowing whether or not the user's device will recognize the Intent.
This is my code which downloads a image from a URL.You can find it useful.Don't forget to add the required permissions for storage,wallpaper and internet.
#Override
public void onClick(View v) {
setWall(v);
}
});
if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (shouldShowRequestPermissionRationale(
Manifest.permission.READ_EXTERNAL_STORAGE)) {
// Explain to the user why we need to read the contacts
}
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
// MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE is an
// app-defined int constant that should be quite unique
return;
}
}
public void setWall(View view) {
new SetWallpaperTask().execute();
}
public class SetWallpaperTask extends AsyncTask <String, Void, Bitmap> {
String image = getIntent().getStringExtra("image");
ProgressDialog progressDialog;
#TargetApi(Build.VERSION_CODES.KITKAT)
#Override
protected Bitmap doInBackground(String... params) {
Bitmap result= null;
try {
result = Picasso.with(getApplicationContext())
.load(image)
.get();
} catch (IOException e) {
e.printStackTrace();
}
WallpaperManager wallpaperManager = WallpaperManager.getInstance(getApplicationContext());
//new Intent(wallpaperManager.getCropAndSetWallpaperIntent(getImageUri(result,getApplicationContext())));
return result;
}
#TargetApi(Build.VERSION_CODES.KITKAT)
#Override
protected void onPostExecute (Bitmap result) {
super.onPostExecute(result);
WallpaperManager wallpaperManager = WallpaperManager.getInstance(getBaseContext());
{
startActivity(new Intent(wallpaperManager.getCropAndSetWallpaperIntent(getImageUri(result,getApplicationContext()))));
// wallpaperManager.setBitmap(result);
progressDialog.dismiss();
// Toast.makeText(getApplicationContext(), "Set wallpaper successfully", Toast.LENGTH_SHORT).show();
}}
#Override
protected void onPreExecute () {
super.onPreExecute();
progressDialog = new ProgressDialog(Wallpaper_activity.this);
progressDialog.setMessage("Please wait...");
progressDialog.setCancelable(false);
progressDialog.show();
}
}
private Uri getImageUri(Bitmap inImage, Context inContext) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(),
inImage, "Title", null);
return Uri.parse(path);
}

Categories

Resources