I'm trying to create something like this: I display 2 buttons, one is called "open gallery", the other "open camera". If I click on the gallery button we open the gallery and choose an image, then crop the image and output the cropped image. If I click camera, we create an image then crop the image and output it.
Now I have: If I first choose gallery always in imgview output crop image from gallery. Even if I choose camera and crop this image. And just same if I choose the camera in imgview always set image only from camera.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imgview = (ImageView) findViewById(R.id.imageView1);
Button buttonCamera = (Button) findViewById(R.id.btn_take_camera);
Button buttonGallery = (Button) findViewById(R.id.btn_select_gallery);
buttonCamera.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
saveFullImage();
} catch (Exception e) {
Log.e("error", e.toString());
}
}
});
buttonGallery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.putExtra("crop", "true");
intent.putExtra("aspectX", 0);
intent.putExtra("aspectY", 0);
intent.putExtra("outputX", 200);
intent.putExtra("outputY", 150);
try {
intent.putExtra("return-data", true);
startActivityForResult(Intent.createChooser(intent,
"Complete action using"), PICK_FROM_GALLERY);
} catch (ActivityNotFoundException e) {
// Do nothing for now
}
}
});
}
public void saveFullImage() {
Intent intent=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File create_dir=new File(Environment.getExternalStorageDirectory()+"/Vsenseloop");
if(!create_dir.exists()){
create_dir.mkdir();
}
File file=new File(Environment.getExternalStorageDirectory()+"/Vsenseloop", "ssasdasdss.jpg");
outputFileUri=Uri.fromFile(file);
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(intent, TAKE_PICTURE);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode==TAKE_PICTURE){
performCrop();
// Check if the result includes a thumbnail Bitmap
if(data!=null){
if(data.hasExtra("data")){
bitmap=data.getParcelableExtra("data");
imgview.setImageBitmap(bitmap);
}
}
}else if(requestCode==PIC_CROP){
// get the returned data
Uri imageUri=data.getData();
if(imageUri==null){
}else{
try{
bitmap=MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
}catch(FileNotFoundException e){
// TODO Auto-generated catch block
e.printStackTrace();
}catch(IOException e){
// TODO Auto-generated catch block
e.printStackTrace();
}
// display the returned cropped image
imgview.setImageBitmap(bitmap);
}
} else if (requestCode == PICK_FROM_GALLERY) {
bitmap = data.getParcelableExtra("data");
imgview.setImageBitmap(bitmap);
}
}
private void performCrop() {
try{
Intent cropIntent=new Intent("com.android.camera.action.CROP", null).setDataAndType(outputFileUri, "image/*").putExtra("crop", "true")
.putExtra("aspectX", 1).putExtra("aspectY", 1).putExtra("outputX", 256).putExtra("outputY", 256).putExtra("scale", true)
.putExtra("return-data", false).putExtra("scaleUpIfNeeded", true).putExtra(MediaStore.EXTRA_OUTPUT, picUri)
.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
startActivityForResult(cropIntent, PIC_CROP);
}catch(ActivityNotFoundException anfe){
// display an error message
String errorMessage="Ваше устройство не поддерживает обрезку фото!";
Toast toast=Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
toast.show();
}
}
Related
I have created an app that you could share images with them. I have set a notification sound when the sharing process is done. However, if I hit Cancel/Back buttons, the sound still plays.
In my code below, I have set a share button, once you click on it, you can share a bitmap of the image through the basic sharing app of android.
How can I set the sound to ONLY play when the sharing is complete.
Thanks,
Safi
Here's my code:
shareBtn = findViewById(R.id.shareButton);
shareBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
v.startAnimation(animTranslate);
shareDigitalCard();
}
});
private void shareDigitalCard() {
if (ActivityCompat.checkSelfPermission(MyMenu.this,
android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
try {
makeStorageRequest();
} catch (Exception e) {
e.printStackTrace();
}
}else {
Bitmap viewBmp = Bitmap.createBitmap(mPager.getWidth(),
mPager.getHeight(), Bitmap.Config.ARGB_8888);
viewBmp.setDensity(mPager.getResources().getDisplayMetrics().densityDpi);
Canvas canvas = new Canvas(viewBmp);
//mPager.layout(0, 0 , mPager.getLayoutParams().width, mPager.getLayoutParams().height);
mPager.draw(canvas);
path = String.valueOf(saveTempBitmap(viewBmp));
shareImage(path);
}
}
private void shareImage(String file) {
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
Intent share = new Intent(Intent.ACTION_SEND);
// If you want to share a png image only, you can do:
// setType("image/png"); OR for jpeg: setType("image/jpeg");
share.setType("image/*");
File imageFileToShare = new File(file);
Uri uri = Uri.fromFile(imageFileToShare);
share.putExtra(Intent.EXTRA_STREAM, uri);
try {
startActivityForResult(Intent.createChooser(share, "Share Image!"),123);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 123){
if (isSoundEnable) {
MediaPlayer player = null;
if (player == null) {
player = MediaPlayer.create(this, R.raw.success);
final MediaPlayer finalPlayer = player;
player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
stopPlayer(finalPlayer);
}
});
}
player.start();
}
} else {
Toast.makeText(this, "An Error Has Occured !", Toast.LENGTH_SHORT).show();
}
}
You cannot get this event. The sharing procedure depends on the other App and you haven't any control or result from it. What you know is just you have send an Intent to a specific App, but what it does it's all up to it.
I have project, I make scan Qr code from gallery image. it works fine. But my problem is my app scanned only qr with black and white color. when I trying to add others qr image with blue and white, it can't read.
This is my code
//call the onactivity result method
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch (requestCode) {
case SELECT_PHOTO:
if (resultCode == RESULT_OK) {
//doing some uri parsing
Uri selectedImage = imageReturnedIntent.getData();
InputStream imageStream = null;
try {
//getting the image
imageStream = getContentResolver().openInputStream(selectedImage);
} catch (FileNotFoundException e) {
Toast.makeText(getApplicationContext(), "File not found", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
//decoding bitmap
Bitmap bMap = BitmapFactory.decodeStream(imageStream);
Scan.setImageURI(selectedImage);// To display selected image in image view
int[] intArray = new int[bMap.getWidth()*bMap.getHeight()];
//copy pixel data from the Bitmap into the 'intArray' array
bMap.getPixels(intArray, 0, bMap.getWidth(), 0, 0, bMap.getWidth(), bMap.getHeight());
RGBLuminanceSource source = new RGBLuminanceSource(bMap.getWidth(), bMap.getHeight(), intArray);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
Reader reader = new MultiFormatReader(); // use this otherwise
// ChecksumException
try {
Hashtable<DecodeHintType, Object> decodeHints = new Hashtable<DecodeHintType, Object>();
decodeHints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
decodeHints.put(DecodeHintType.PURE_BARCODE, Boolean.TRUE);
final Result result = reader.decode(bitmap, decodeHints);
//*I have created a global string variable by the name of barcode to easily manipulate data across the application*//
barcode = result.getText().toString();
//do something with the results for demo i created a popup dialog
if(barcode!=null){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Scan Result");
builder.setIcon(R.mipmap.ic_launcher);
builder.setMessage("" + barcode);
AlertDialog alert1 = builder.create();
alert1.setButton(DialogInterface.BUTTON_POSITIVE, "Done", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent i = new Intent (getBaseContext(),MainActivity.class);
startActivity(i);
}
});
alert1.setCanceledOnTouchOutside(false);
alert1.show();}
else
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Scan Result");
builder.setIcon(R.mipmap.ic_launcher);
builder.setMessage("Nothing found try a different image or try again");
AlertDialog alert1 = builder.create();
alert1.setButton(DialogInterface.BUTTON_POSITIVE, "Done", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent i = new Intent (getBaseContext(),MainActivity.class);
startActivity(i);
}
});
alert1.setCanceledOnTouchOutside(false);
alert1.show();
}
//the end of do something with the button statement.
} catch (NotFoundException e) {
Toast.makeText(getApplicationContext(), "Nothing Found", Toast.LENGTH_SHORT).show();
e.printStackTrace();
} catch (ChecksumException e) {
Toast.makeText(getApplicationContext(), "Something weird happen, i was probably tired to solve this issue", Toast.LENGTH_SHORT).show();
e.printStackTrace();
} catch (FormatException e) {
Toast.makeText(getApplicationContext(), "Wrong Barcode/QR format", Toast.LENGTH_SHORT).show();
e.printStackTrace();
} catch (NullPointerException e) {
Toast.makeText(getApplicationContext(), "Something weird happen, i was probably tired to solve this issue", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
}
}
im trying to have my apps submit button not clickable until the user takes a picture. so initially the button will be not clickable and then when the person takes a picture the submit button becomes clickable so they can move on. problem is i cant get it to work properly. as of right now the submit button is not clickable (which is what i want) when it first loads. but if i hit the camera button then press the back button the submit button becomes visible(i want it to be unclickable). how can i correct this so that it doesnt show the submit button during this situation? o far i have tried to set not clickable in the oncreate method , and i set to clickable when the image file is made in the photobutton. which didnt work.
public class TreeQuestionsActivity extends AppCompatActivity {
Button btnSubmit;
Button btnPhoto;
ProgressBar progress;
String mCurrentPhotoPath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tree_questions_list);
btnSubmit = (Button) findViewById(R.id.enter_button);
btnPhoto = (Button) findViewById(R.id.photo_button);
btnSubmit.setEnabled(false);
}
private void setupButton() {
btnSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selection();
if (mCurrentPhotoPath == null) {
Toast.makeText(getApplicationContext(), "Please submit a picture of the tree before you move on",
Toast.LENGTH_LONG).show();
} else if (f == false) {
showProgress(true);
new UploadTreeTask().execute(); //adds tree and then adds the dailyUpdate -> Goes to bird list activity
//new DbInsertTask().execute();
} else {
showProgress(true);
treeID = tree.getId();
new UploadDailyTask().execute();
}
}
});
btnPhoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
//startActivityForResult(takePictureIntent, ACTIVITY_START_CAMERA);
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException e) {
// Error occurred while creating the File
Log.i(Constants.TAG, "IO Exception");
e.printStackTrace();
}
// Continue only if the File was successfully created
if (photoFile != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
btnSubmit.setEnabled(true);
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
});
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "TREE_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = image.getAbsolutePath();
Log.d(Constants.TAG, mCurrentPhotoPath);
return image;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case ACTIVITY_START_CAMERA:
if (requestCode == ACTIVITY_START_CAMERA && resultCode == RESULT_OK & null != data) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
//to generate random file name
String fileName = "tempimg.jpg";
try {
Bitmap photo = (Bitmap) data.getExtras().get("data");
//captured image set in imageview
imageView.setImageBitmap(photo);
} catch (Exception e) {
e.printStackTrace();
}
}
}
super.onActivityResult(requestCode, resultCode, data);
}
}
move this line
btnSubmit.setEnabled(true);
to onActivityResult() method after this line
imageView.setImageBitmap(photo);
your code looks fine but i think it would look better if you just played with the visibility of the button:
btnSubmit.setVisibility(View.GONE);
btnSubmit.setVisibility(View.VISIBLE);
and you have to to add :
btnSubmit.setEnabled(true);
into your onActivityResult() method
I have screenshot button and when i take screenshot, image should be stored in the sd card and when i going to see the gallery they display the image.
But, I want to when i take screenshot at a time, to be display in the image viewer app.
My Code Here:
public class MainActivity extends Activity {
Button captureImage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
captureImage = (Button)findViewById(R.id.captureImage);
captureImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Bitmap bitmap = takeScreenshot();
saveBitmap(bitmap);
}
private void saveBitmap(Bitmap bitmap) {
// TODO Auto-generated method stub
File imagePath = new File(Environment.getExternalStorageDirectory() + "/DCIM/Camera/"+"MyProfile.JPEG");
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,Uri.fromFile(imagePath)));
FileOutputStream fos;
try {
fos = new FileOutputStream(imagePath);
bitmap.compress(CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
Toast.makeText(getApplicationContext(), "Screen short saved", Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
Toast.makeText(getApplicationContext(), "File not found", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "something wrong", Toast.LENGTH_SHORT).show();
}
}
private Bitmap takeScreenshot() {
// TODO Auto-generated method stub
View rootView = findViewById(android.R.id.content).getRootView();
rootView.setDrawingCacheEnabled(true);
return rootView.getDrawingCache();
}
});
}
Manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Screenshot:
I need out put like this
After I take a picture I store the picture into ImageView, So if anyone has an idea or suggestion in how to store the picture after it shown on the ImageView into phone stage without user interaction
Thanks in advance
public class MainActivity extends Activity {
ImageView viewpict;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewpict=(ImageView) findViewById(R.id.pict_result);
Button btn= (Button)findViewById(R.id.camera);
btn.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
Intent intent = new Intent (android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
// Intent intent = new Intent (getApplicationContext(),MainActivity2.class);
//startActivity(intent);
startActivityForResult(intent,0);
}
});
}
protected void onActivityResult( int requestCode, int resultCode,Intent data)
{
if (requestCode==0)
{
Bitmap theimage = (Bitmap) data.getExtras().get("data");
viewpict.setImageBitmap(theimage);
}
}
}
Try:
viewpict.buildDrawingCache();
Bitmap bm=viewpict.getDrawingCache();
And save:
OutputStream fOut = null;
Uri outputFileUri;
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 {
bm.compress(Bitmap.CompressFormat.PNG, 100, fOut);
fOut.flush();
fOut.close();
} catch (Exception e) {
}
And permission in AndroidManifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />