take photo but not OCR: android studio - java

I combined the two Java codes, but I have a problem: when I take a picture and then I want to read the text with this picture, it writes the text of the program-assigned image (not taken photo).
The problem is the combination of commands, which I can not sort. Always read the original image (ImageView is installed with a Bitmap test image).
I tried many times but could not order.
P.S I do not want to save the captured image.
Thanks in advance for the feedback.
my Java code:
public class MainActivity extends AppCompatActivity {
private static final int CAMERA_REQUEST = 1888; ///////
private ImageView imageView;///
private static final int MY_CAMERA_PERMISSION_CODE = 100;////
////////////
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults)
{
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == MY_CAMERA_PERMISSION_CODE)
{
if (grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
Toast.makeText(this, "camera permission granted", Toast.LENGTH_LONG).show();
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
else
{
Toast.makeText(this, "camera permission denied", Toast.LENGTH_LONG).show();
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_REQUEST && resultCode == Activity.RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
}
}/////////////
ImageView imageview;
Button btnProcess;
EditText txtView, txtVieww;
Bitmap photo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.imageView = (ImageView)this.findViewById(R.id.image_view);////
Button photoButton = (Button) this.findViewById(R.id.button1);////
imageview = findViewById(R.id.image_view);
btnProcess = findViewById(R.id.btnProcess);
txtView = findViewById(R.id.txtView);
txtVieww = findViewById(R.id.txtVieww);
photo = BitmapFactory.decodeResource(getApplicationContext().getResources(),
R.drawable.newyt);
imageview.setImageBitmap(photo);
/////
photoButton.setOnClickListener(v -> {
if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED)
{
requestPermissions(new String[]{Manifest.permission.CAMERA}, MY_CAMERA_PERMISSION_CODE);
}
else
{
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
});
///////
btnProcess.setOnClickListener(v -> {
TextRecognizer txtRecognizer = new TextRecognizer.Builder(getApplicationContext()).build();
if (!txtRecognizer.isOperational()) {
txtView.setText(R.string.error_prompt);
txtVieww.setText(R.string.error_prompt);
} else {
Frame frame = new Frame.Builder().setBitmap(photo).build();
SparseArray<TextBlock> items = txtRecognizer.detect(frame);
StringBuilder strBuilder = new StringBuilder();
for (int i = 0; i < items.size(); i++) {
TextBlock item = items.valueAt(i);
strBuilder.append(item.getValue());
strBuilder.append("/");
for (Text line : item.getComponents()) {
//extract scanned text lines here
Log.v("lines", line.getValue());
for (Text element : line.getComponents()) {
//extract scanned text words here
Log.v("element", element.getValue());
}
}
}
final String substringi = strBuilder.substring(0, 10).replaceAll("\\s+", "");
final String substringg = substringi.substring(0, 5);
txtView.setText(substringi);
txtVieww.setText(substringg);
}
});
}
}

Related

How to add an image captured on camera to imageviewer in Android using java? I have tried the following code

I have added Camera permissions as well which is working perfectly but the image view is not holding the image that is captured. The manifest file is also proper still. The app isn't crashing even it is not showing any errors as well. And I even want to add the image to the database.
public class RiderProfile extends AppCompatActivity {
ImageView imgDp,imgDlFront,imgDlback;
TextView txtDp,txtDl;
Button btnSave;
public static final int CAMERA_REQUEST = 1888;
private static final String TAG = "1111";
private static final int MY_CAMERA_PERMISSION_CODE = 100;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rider_profile);
imgDp = (ImageView)findViewById(R.id.imgDp);
imgDlFront = (ImageView)findViewById(R.id.imgDlFront);
imgDlback = (ImageView)findViewById(R.id.imgDlback);
txtDp = (TextView) findViewById(R.id.txtDp);
txtDl = (TextView)findViewById(R.id.txtDl);
btnSave = (Button) findViewById(R.id.btnSave);
imgDp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(i, CAMERA_REQUEST);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == Activity.RESULT_OK) {
Bitmap photo1 = (Bitmap) data.getExtras().get("data");
Log.d(TAG, "onActivityResult: click ");
imgDp.setImageBitmap(photo1);
}
}
});
imgDlFront.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(i, CAMERA_REQUEST);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == Activity.RESULT_OK) {
Bitmap photo2 = (Bitmap) data.getExtras().get("data");
Log.d(TAG, "onActivityResult: click ");
imgDlFront.setImageBitmap(photo2);
}
}
});
imgDlback.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(i, CAMERA_REQUEST);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == Activity.RESULT_OK) {
Bitmap photo3 = (Bitmap) data.getExtras().get("data");
Log.d(TAG, "onActivityResult: click ");
imgDlback.setImageBitmap(photo3);
}
}
});
}
}
1. #Override
public void onCameraOpen() {
Intent pictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (pictureIntent.resolveActivity(getPackageManager()) != null) {
try {
imageFile = CameraUtils.createImageFile(this);
} catch (IOException e) {
e.printStackTrace();
return;
}
imageUri = FileProvider.getUriForFile(this, getPackageName() + ".provider", imageFile);
pictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(pictureIntent, IntentRequestCode.RESULT_CODE_IMAGE_CAPTURE);
}
}
2. #Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case RESULT_CODE_IMAGE_CAPTURE:
if (resultCode == RESULT_OK) {
onCaptureImage(imageFile, imageUri);
} else {
Toast.makeText(this, "Camera canceled", Toast.LENGTH_SHORT).show();
}
break;
}
}
3. void onCaptureImage(File imageFile, Uri imageUri) {
Uri uri = Uri.fromFile(imageFile);
String selectedImagePath = CameraUtils.getPath(application, uri);
File file1 = new File(selectedImagePath);
if (file1.length() != 0) {
FileAttachments b_data = new FileAttachments();
b_data.setFileName(file1.getName());
CameraUtils.writeScaledDownImage(file1, getApplication());
b_data.setFile(file1);
}
}

How to recognize landmarks using Firebase ML kit?

I'm creating an application for recognizing landmarks.
When the image is recognized, the result should fall to onSuccess, but instead comes to onFailure.
The following message is displayed in the Log:
If you have not set up billing, please go to the Firebase Console to set up billing: https://firebase.corp.google.com/u/0/project/_/overview?purchaseBillingPlan= true
If you are specifying a debug API Key override and turning on API Key restrictions, make sure the restrictions are set up correctly.
When I click on the link I see the following page:
https://login.corp.google.com/request?s=firebase.corp.google.com:443/uberproxy/&d=https://firebase.corp.google.com/u/0/project/_/overview%3FpurchaseBillingPlan%3Dtrue%26upxsrf%3DAKKYJRc2HD6ROcy9V9DxnYxw-pd8yGnml-oEi37m5hKhkWurWQ:1557057663745&maxAge=1200&authLevel=2000000&keyIds=X-q,k02
What will I need to to do?
public class RecognizeLandmarks extends AppCompatActivity {
EditText mResultEt;
ImageView mPreviewIv;
TextView tvLName, tvLiD, tvLConfidence, tvLlatitude, tvLlongitude;
public static final int CAMERA_REQUEST_CODE = 200;
public static final int STORAGE_REQUEST_CODE = 400;
public static final int IMAGE_PIC_GALLERY_CODE = 1000;
public static final int IMAGE_PIC_CAMERA_CODE = 1001;
private static final String TAG = "MyLog";
String cameraPermission[];
String storagePermission[];
Uri image_uri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recognize_landmarks);
androidx.appcompat.app.ActionBar actionBar = getSupportActionBar();
actionBar.setSubtitle("Click image button to insert Image");
mResultEt = findViewById(R.id.resultEt);
mPreviewIv = findViewById(R.id.imageIv);
tvLName = findViewById(R.id.tvLName);
tvLiD = findViewById(R.id.tvLiD);
tvLConfidence = findViewById(R.id.tvLConfidence);
tvLlatitude = findViewById(R.id.tvLlatitude);
tvLlongitude = findViewById(R.id.tvLlongitude);
//camera permission
cameraPermission = new String[]{Manifest.permission.CAMERA,
Manifest.permission.WRITE_EXTERNAL_STORAGE};
//storage permission
storagePermission = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE};
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
//inflate menu
getMenuInflater().inflate(R.menu.menu_recognize_text, menu);
return true;
}
//handle actionbar item clicks
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId( );
if (id == R.id.addImage) {
showImageImportDialog( );
}
if (id == R.id.settings) {
Toast.makeText(this, "Settings", Toast.LENGTH_SHORT).show( );
}
return super.onOptionsItemSelected(item);
}
private void showImageImportDialog() {
// items to display in dialog
String[] items = {" Camera", " Gallery"};
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setTitle("Select Image");
dialog.setItems(items, new DialogInterface.OnClickListener( ) {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
if (i == 0) {
//camera option clicked
/*for os Marshmallow and above we need to ask runtime permission for camera and storage*/
if (!checkCameraPermission()) {
//camera permission not allowed, request it
requestCameraPermission();
} else {
//permission allowed, take picture
pickCamera();
}
}
if (i == 1) {
//gallery option clicked
if (!checkStoragePermission()) {
//storage permission not allowed, request it
requestStoragePermission();
} else {
//permission allowed, take picture
pickGallery();
}
}
}
});
dialog.create().show();
}
private void pickGallery() {
//intent to pick image from gallery
Intent intent = new Intent(Intent.ACTION_PICK);
//set intent type to image
intent.setType("image/*");
startActivityForResult(intent, IMAGE_PIC_GALLERY_CODE);
}
private void pickCamera() {
//intent to take image from camera, it will also be save to storage to get high quality image
ContentValues values = new ContentValues( );
values.put(MediaStore.Images.Media.TITLE, "NewPic"); //title of the picture
values.put(MediaStore.Images.Media.DESCRIPTION, "Image to text"); //description
image_uri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, image_uri);
startActivityForResult(cameraIntent, IMAGE_PIC_CAMERA_CODE);
}
private void requestStoragePermission() {
ActivityCompat.requestPermissions(this, storagePermission, STORAGE_REQUEST_CODE);
}
private boolean checkStoragePermission() {
boolean result = ContextCompat.checkSelfPermission(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE) == (PackageManager.PERMISSION_GRANTED);
return result;
}
private void requestCameraPermission() {
ActivityCompat.requestPermissions(this, cameraPermission, CAMERA_REQUEST_CODE);
}
private boolean checkCameraPermission() {
/*Check camera permission and return the result
* in order to get high quality image we have to save image to external storage first
* before inserting to image view that`s why storage permission will also be required */
boolean result = ContextCompat.checkSelfPermission(this,
Manifest.permission.CAMERA) == (PackageManager.PERMISSION_GRANTED);
boolean result1 = ContextCompat.checkSelfPermission(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE) == (PackageManager.PERMISSION_GRANTED);
return result && result1;
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case CAMERA_REQUEST_CODE:
if (grantResults.length > 0) {
boolean cameraAccepted = grantResults[0] ==
PackageManager.PERMISSION_GRANTED;
boolean writeStorageAccepted = grantResults[0] ==
PackageManager.PERMISSION_GRANTED;
if (cameraAccepted && writeStorageAccepted) {
pickCamera();
} else {
Toast.makeText(this, "permission denied", Toast.LENGTH_SHORT).show( );
}
}
break;
case STORAGE_REQUEST_CODE:
if (grantResults.length > 0) {
boolean writeStorageAccepted = grantResults[0] ==
PackageManager.PERMISSION_GRANTED;
if (writeStorageAccepted) {
pickGallery( );
}
else {
Toast.makeText(this, "permission denied", Toast.LENGTH_SHORT).show( );
}
}
break;
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
//got image from camera or gallery
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == IMAGE_PIC_GALLERY_CODE) {
//got image from gallery now crop it
CropImage.activity(data.getData( ))
.setGuidelines(CropImageView.Guidelines.ON) // enable image guidelines
.start(this);
}
if (requestCode == IMAGE_PIC_CAMERA_CODE) {
//got image from camera crop it
CropImage.activity(image_uri)
.setGuidelines(CropImageView.Guidelines.ON) // enable image guidelines
.start(this);
}
}
//get cropped image
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result1 = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
Uri resultUri = result1.getUri( ); // get image uri
//set image to image view
mPreviewIv.setImageURI(resultUri);// past image in iV
//get drawable bitmap for text recognition
BitmapDrawable bitmapDrawable = (BitmapDrawable) mPreviewIv.getDrawable( );
Bitmap bitmap = bitmapDrawable.getBitmap( );
FirebaseVisionImage image = FirebaseVisionImage.fromBitmap(bitmap);
FirebaseVisionCloudDetectorOptions options =
new FirebaseVisionCloudDetectorOptions.Builder( )
.setModelType(FirebaseVisionCloudDetectorOptions.LATEST_MODEL)
.setMaxResults(15)
.build( );
FirebaseVisionCloudLandmarkDetector detector = FirebaseVision.getInstance( )
.getVisionCloudLandmarkDetector(options);
Task<List<FirebaseVisionCloudLandmark>> result = detector.detectInImage(image)
.addOnSuccessListener(new OnSuccessListener<List<FirebaseVisionCloudLandmark>>( ) {
#Override
public void onSuccess(List<FirebaseVisionCloudLandmark> firebaseVisionCloudLandmarks) {
// Task completed successfully
// ...
for(FirebaseVisionCloudLandmark landmark : firebaseVisionCloudLandmarks) {
//Rect bounds = landmark.getBoundingBox();
String landmarkName = landmark.getLandmark( );
tvLName.setText(landmarkName);
String entityId = landmark.getEntityId( );
tvLiD.setText(entityId);
float confidence = landmark.getConfidence( );
tvLConfidence.setText(Float.toString(confidence));
// Multiple locations are possible, e.g., the location of the depicted
// landmark and the location the picture was taken.
for(FirebaseVisionLatLng loc : landmark.getLocations( )) {
double latitude = loc.getLatitude( );
tvLlatitude.setText(Double.toString(latitude));
double longitude = loc.getLongitude( );
tvLlongitude.setText(Double.toString(longitude));
}
}
}
})
.addOnFailureListener(new OnFailureListener( ) {
#Override
public void onFailure(#NonNull Exception e) {
// Task failed with an exception
// ...
Log.d(TAG,e.getMessage());
Toast.makeText(RecognizeLandmarks.this, "Recognizing Failed", Toast.LENGTH_SHORT).show( );
}
});
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
//if there is any error show it
Exception error = result1.getError( );
Toast.makeText(this, "" + error, Toast.LENGTH_SHORT).show( );
}
}
}
}
Result
D/MyLog: If you haven't set up billing, please go to Firebase console to set up billing: https://firebase.corp.google.com/u/0/project/_/overview?purchaseBillingPlan=true. If you are specifying a debug Api Key override and turned on Api Key restrictions, make sure the restrictions are set up correctly
ML Kit's landmark detection does not run on the device itself, but uses Google Cloud Vision. For this reason your project needs to be on a paid plan, before you can use landmark detection. The first 1000 calls are free, after which you will be charged for additional calls.

How can save camera photo in a file of mobile device?

There is camera codes in my project that another developer who wrote. It takes photo by the device camera but it doesn't save photo in a file of device. It must to save the photo in a file of mobile device. I post here java class and other codes that is related with camera. How can save the photo in device?
SendMessagePage.java
public class SendMessagePage extends BaseActivity {
private static final int CAMERA_RQ = 6969;
private static final int PERMISSION_RQ = 84;
File saveDir = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) {
saveDir = new File(Environment.getExternalStorageDirectory(), "MaterialCamera");
saveDir.mkdirs();
}
final MaterialCamera materialCamera =
new MaterialCamera(this)
.saveDir(saveDir)
.showPortraitWarning(true)
.allowRetry(true)
.defaultToFrontFacing(true)
.allowRetry(true)
.autoSubmit(false)
.labelConfirm(R.string.mcam_use_video);
LinearLayout takePhoto = (LinearLayout) findViewById(R.id.take_photo);
takePhoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (ContextCompat.checkSelfPermission(SendMessagePage.this,
Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(SendMessagePage.this,
Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
} else {
if (1 == 2) {
}
ActivityCompat.requestPermissions(SendMessagePage.this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 23
);
}
}
saveDir = new File(Environment.getExternalStorageDirectory(), "MaterialCamera");
saveDir.mkdirs();
materialCamera
.stillShot() // launches the Camera in stillshot mode
.labelConfirm(R.string.mcam_use_stillshot);
materialCamera.start(CAMERA_RQ);
}
});
}
private String readableFileSize(long size) {
if (size <= 0) return size + " B";
final String[] units = new String[]{"B", "KB", "MB", "GB", "TB"};
int digitGroups = (int) (Math.log10(size) / Math.log10(1024));
return new DecimalFormat("#,##0.##").format(size / Math.pow(1024, digitGroups))
+ " "
+ units[digitGroups];
}
private String fileSize(File file) {
return readableFileSize(file.length());
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Received recording or error from MaterialCamera
if (requestCode == CAMERA_RQ) {
if (resultCode == RESULT_OK) {
final File file = new File(data.getData().getPath());
Toast.makeText(
this,
String.format("Saved to: %s, size: %s", file.getAbsolutePath(), fileSize(file)),
Toast.LENGTH_LONG)
.show();
} else if (data != null) {
Exception e = (Exception) data.getSerializableExtra(MaterialCamera.ERROR_EXTRA);
if (e != null) {
e.printStackTrace();
Toast.makeText(this, "Error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
}
#Override
public void onRequestPermissionsResult(
int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
Toast.makeText(
this,
"Videos will be saved in a cache directory instead of an external storage directory since permission was denied.",
Toast.LENGTH_LONG)
.show();
}
}
Define this in your class
private static final int CAMERA_REQUEST = 1888;
private static final int MY_CAMERA_PERMISSION_CODE = 100;
Uri picUri;
File imagefile;
Use the below code for capturing picture. The picture is saved in DCIM folder
takePicture.setOnClickListener(new View.OnClickListener() {
#TargetApi(Build.VERSION_CODES.M)
#Override
public void onClick(View v) {
if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.CAMERA}, MY_CAMERA_PERMISSION_CODE);
} else {
File pictureDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
String pictureName = getPictureName();
imagefile = new File(pictureDirectory, pictureName);
picUri = Uri.fromFile(imagefile);
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, picUri);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
}
});
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_REQUEST && resultCode == Activity.RESULT_OK) {
imageView.setImageURI(picUri);
}
}
private String getPictureName() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
String timestamp = sdf.format(new Date());
nameOfFile=timestamp + ".jpg";
return timestamp + ".jpg";
}
NOTE: This code is working and has no errors as i have used this code in one of my projects. It has been extracted from code of mine.

The app I created won't allow me to save pictures?

The app is allowing me to capture pictures, then allowing me to accept or reject pictures, showing me accepted images inside the app but not saving them to the device. All help much appreciated?
public class MainActivity extends AppCompatActivity {
private Button takePictureButton;
private ImageView imageView;
private Uri file;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
takePictureButton = (Button) findViewById(R.id.button_image);
imageView = (ImageView) findViewById(R.id.imageview);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
takePictureButton.setEnabled(false);
ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE }, 0);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == 0) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED
&& grantResults[1] == PackageManager.PERMISSION_GRANTED) {
takePictureButton.setEnabled(true);
}
}
}
public void takePicture(View view) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
file = Uri.fromFile(getOutputMediaFile());
intent.putExtra(MediaStore.EXTRA_OUTPUT, file);
startActivityForResult(intent, 100);
}
private static File getOutputMediaFile(){
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "Demo");
if (!mediaStorageDir.exists()){
if (!mediaStorageDir.mkdirs()){
Log.d("Demo", "failed to create directory");
return null;
}
}
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
return new File(mediaStorageDir.getPath() + File.separator +
"IMG_"+ timeStamp + ".jpg");
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 100) {
if (resultCode == RESULT_OK) {
imageView.setImageURI(file);
}
}
}
}
Check if you have the right storage permissions.
I suggest you to move the image and then rename it;

show image form gallery in fragment dont work

I'm open gallery from one of my fragment but after i select image from gallery
the image doesn't show to me in view.
in the onActivityResult I have error in the rootview in this line:
ImageView imgView = (ImageView) rootview.findViewById(R.id.imgView);
and I test with toast to show me the selected image path but
it doesnt show me the path.
here is my fragment code:
public class Share_Page extends Fragment implements View.OnClickListener {
private static final int RESULT_OK = 1;
String path="";
String imgPath, fileName;
private Button home_page,search_page;
private static int RESULT_LOAD_IMG = 1;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootview = inflater.inflate(R.layout.share, container, false);
home_page = (Button) rootview.findViewById(R.id.home_page);
search_page = (Button) rootview.findViewById(R.id.search_page);
rootview.findViewById(R.id.buttonLoadPicture).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
loadImagefromGallery();
}
});
btn_click();
return rootview;
}
public void loadImagefromGallery() {
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK
&& null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getActivity().getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imgPath = cursor.getString(columnIndex);
cursor.close();
//ImageView imgView = (ImageView) findViewById(R.id.imgView);
ImageView imgView = (ImageView) rootview.findViewById(R.id.imgView);
imgView.setImageBitmap(BitmapFactory
.decodeFile(imgPath));
String fileNameSegments[] = imgPath.split("/");
fileName = fileNameSegments[fileNameSegments.length - 1];
path=imgPath;
} else {
Toast.makeText(getActivity(), "image not select",
Toast.LENGTH_LONG).show();
imgPath="2";
}
} catch (Exception e) {
Toast.makeText(getActivity(), "error`enter code here`...!", Toast.LENGTH_LONG)
.show();
}
}
This method is for intent to open gallery and pick image:
public void loadImagefromGallery(View view) {
Intent galleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityIfNeeded(galleryIntent, RESULT_LOAD_IMG);
}
And here is result after a image picked. As u see i use image to change a background, u can put it into imageView or what ever u wanted
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK
&& null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
assert cursor != null;
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String imgDecodableString = cursor.getString(columnIndex);
cursor.close();
Drawable d = new BitmapDrawable(getResources(), imgDecodableString);
relativeLayout.setBackground(d);
} else {
Toast.makeText(this, "You haven't picked Image",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG)
.show();
}
}
Also please remember to add a permissions in Manifest
Example how to use a permissions runtime, paste it into Activity
private static final int REQUEST_CODE_EXTERNAL_STORAGE = 1;
private static final int REQUEST_CODE_CAMERA = 2;
private static int RESULT_LOAD_IMG = 1;
#TargetApi(23)
public void checkCameraPermission(){
if(Build.VERSION.SDK_INT < Build.VERSION_CODES.M){
return;
}
if (this.checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[] {Manifest.permission.CAMERA}, REQUEST_CODE_CAMERA);
}
}
#TargetApi(23)
public void checkStoragePermission() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
return;
}
if (this.checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager
.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
REQUEST_CODE_EXTERNAL_STORAGE);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[]
grantResults) {
switch (requestCode) {
case REQUEST_CODE_EXTERNAL_STORAGE:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Thanks for your permission", LENGTH_SHORT).show();
} else {
Toast.makeText(this, "We need your permission to save image",
LENGTH_SHORT).show();
}
break;
case REQUEST_CODE_CAMERA:
if(grantResults[0] == PackageManager.PERMISSION_GRANTED){
Toast.makeText(this, "Thanks for your permission", LENGTH_SHORT).show();
} else {
Toast.makeText(this, "We need your permission to start SOS",
LENGTH_SHORT).show();
}
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
break;
}
}
And if u want to check permissions on fragment u should do like this:
((Activity) getContext()).checkAnyPermission();
u should check this after u open a gallery

Categories