I've simple app for capturing image using Camera using following code
#AfterPermissionGranted(RC_STORAGE_PERMS)
private void launchCamera() {
Log.d(TAG, "launchCamera");
// Check that we have permission to read images from external storage.
String perm = android.Manifest.permission.READ_EXTERNAL_STORAGE;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
&& !EasyPermissions.hasPermissions(this, perm)) {
EasyPermissions.requestPermissions(this, getString(R.string.rationale_storage),
RC_STORAGE_PERMS, perm);
return;
}
// Create intent
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Choose file storage location
File file = new File(Environment.getExternalStorageDirectory(), UUID.randomUUID().toString() + ".jpg");
mFileUri = Uri.fromFile(file);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mFileUri);
// Launch intent
startActivityForResult(takePictureIntent, RC_TAKE_PICTURE);
}
now I want to upload that image to Firebase storage
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.d(TAG, "onActivityResult:" + requestCode + ":" + resultCode + ":" + data);
if (requestCode == RC_TAKE_PICTURE) {
if (resultCode == RESULT_OK) {
if (mFileUri != null) {
uploadFromUri(mFileUri);
} else {
Log.w(TAG, "File URI is null");
}
} else {
Toast.makeText(this, "Taking picture failed.", Toast.LENGTH_SHORT).show();
}
}
}
private void uploadFromUri(Uri fileUri) {
Log.d(TAG, "uploadFromUri:src:" + fileUri.toString());
// [START get_child_ref]
// Get a reference to store file at photos/<FILENAME>.jpg
final StorageReference photoRef = mStorageRef.child("photos")
.child(fileUri.getLastPathSegment());
// [END get_child_ref]
// Upload file to Firebase Storage
// [START_EXCLUDE]
showProgressDialog();
// [END_EXCLUDE]
Log.d(TAG, "uploadFromUri:dst:" + photoRef.getPath());
photoRef.putFile(fileUri)
.addOnSuccessListener(this, new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// Upload succeeded
Log.d(TAG, "uploadFromUri:onSuccess");
// Get the public download URL
mDownloadUrl = taskSnapshot.getMetadata().getDownloadUrl();
Log.w("IMAGE_URL", "Path is " + mDownloadUrl.toString());
uploadedImage = (ImageView) findViewById(R.id.uploaded_img);
try{// Here I'm setting image in ImageView
uploadedImage.setImageURI(mDownloadUrl);
}catch (Exception e){
System.out.print(e.getCause());
}
// [START_EXCLUDE]
hideProgressDialog();
///updateUI(mAuth.getCurrentUser());
// [END_EXCLUDE]
}
})
);
}
in uploadFromUri() at line
try{// Here I'm setting image in ImageView
uploadedImage.setImageURI(mDownloadUrl);
}catch (Exception e){
System.out.print(e.getCause());
}
image is not set in ImageView and I get error
07-29 09:54:23.055 18445-18445/? W/IMAGE_URL: Path is https://firebasestorage.googleapis.com/v0/b/connectin-a74da.appspot.com/o/photos%2F7dd3d46f-ed7b-4020-bc89-fd9e19a8ec65.jpg?alt=media&token=5b4f9ad7-1e99-42b8-966d-50c74fc2eab6
07-29 09:54:23.056 18445-18445/? E/BitmapFactory: Unable to decode stream: java.io.FileNotFoundException: https:/firebasestorage.googleapis.com/v0/b/connectin-a74da.appspot.com/o/photos%2F7dd3d46f-ed7b-4020-bc89-fd9e19a8ec65.jpg?alt=media&token=5b4f9ad7-1e99-42b8-966d-50c74fc2eab6: open failed: ENOENT (No such file or directory)
and if I open this link I see image there, question is why it is not set in image view
setImageURI() is for content URIs particular to the Android
platform, not URIs specifying Internet resources.
Try getting your bitmap from internet in a new thread an then add it to your ImageView. Like this:
uploadedImage.setImageBitmap(getImageBitmap(mDownloadUrl));
private Bitmap getImageBitmap(String url) {
Bitmap bm = null;
try {
URL aURL = new URL(url);
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
bm = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
} catch (IOException e) {
Log.e(TAG, "Error getting bitmap", e);
}
return bm;
}
You also can use a useful library to set image (Internal and external images) called Picasso http://square.github.io/picasso/
Add Picasso library for image loading and use the following code.
Picasso.with(activity).load(imageURL)
.resize(imageWidth,imageHeight)
.into(imageView, new Callback() {
#Override
public void onSuccess() {
Log.d(TAG,"successfully load the image");
}
#Override
public void onError() {
Log.d(TAG,"fail to load the image");
}
});
Related
This contents of this loadImage method never gets called although I am calling this method in OnActivityResult.
public void loadImage(Uri uri){
File file = new File(getApplicationContext().getExternalCacheDir().getAbsolutePath() + "/" +uid + ".jpg");
Log.d("Check Bitmap", "file" + file);
try {
Picasso picasso = Picasso.get();
Bitmap bitmap = picasso.load(uri).get();
Log.d("Check Bitmap", "bitmap working");
bitmap.compress(Bitmap.CompressFormat.JPEG, 100,new FileOutputStream(file));
} catch (Exception e) {
Log.d("Check Bitmap", "bitmap not working, cached");
e.printStackTrace();
}
My aim is to retrieve the image from the file.
This is my OnActivityResult
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode ==1000){
{
if(resultCode == Activity.RESULT_OK){
imageUri = data.getData();
Context context;
final ProgressDialog dialog = new ProgressDialog(myProfile.this);
dialog.setMessage("Uploading Image...");
dialog.show();
profilepic.setImageURI(imageUri);
ref.putFile(imageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
ref.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
final Picasso picasso = Picasso.get();
picasso.setIndicatorsEnabled(true);
picasso.load(uri).into(profilepic);
downloadUri = uri;
dialog.dismiss();
Toast.makeText(getApplicationContext(), "Image Uploaded!", Toast.LENGTH_SHORT).show();
loadImage(uri); //Here I call
You should not use space separated TAG for logs. Try replacing your "Check Bitmap" with something of one word (eg. "Checkere"). Then you will be able to see your Log in your Logcat.
You need to put everything inside a thread.
Here is the complete block of code for loadImage
public void loadImage(final Uri uri){
Thread thread = new Thread() {
#Override
public void run() {
Log.d("Checkere", "stuck at file");
File file = new File(getCacheDir() + File.separator + uid + ".jpg");
Log.d("Checkere", "file" + file);
try {
Picasso picasso = Picasso.get();
Bitmap bitmap = picasso.load(uri).get();
Log.d("Checkere", "bitmap working");
FileOutputStream fOut = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 85, fOut);
fOut.flush();
fOut.close();
} catch (Exception e) {
Log.d("Checkere", e.getMessage());
e.printStackTrace();
}
}};
thread.start();
}
Note that I have also added these two lines in your code.
fOut.flush();
fOut.close();
I hope this helps!
In Android studio , in my app the image is not getting replaced with the bitmap I create,the path is correct but the ic_action_android is not getting replaced with my fresh captured image.
In OnCreate:
btOpen.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
//Open Camera
// Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if(cameraIntent.resolveActivity(getPackageManager())!=null)
{
File imageFile= null;
try{
imageFile = getImageFile();
}catch(IOException e){
Toast.makeText(getApplicationContext(), "get image file failed", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
if(imageFile != null)
{
Uri imageUri= FileProvider.getUriForFile(MainActivity.this,"com.example.android.provider",imageFile);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri);
startActivityForResult(cameraIntent,IMAGE_REQUEST);
}
else
{
Toast.makeText(getApplicationContext(), "Imagefile is null", Toast.LENGTH_SHORT).show();
}
}
//startActivityForResult(intent,100);
}
});
private File getImageFile()throws IOException
{
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageName="jpg_"+timeStamp+"_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File imageFile = File.createTempFile(imageName,".jpg",storageDir);
currentImagePath= imageFile.getAbsolutePath();
return imageFile;
}
The on Activity result:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
ImageView imageView= new ImageView(MainActivity.this);
imageView.setImageResource(R.drawable.ic_action_android);
addView(imageView,1000,1000);
Log.i(TAG, "The image path is " + currentImagePath);
final Bitmap mBitmap= BitmapFactory.decodeFile(getIntent().getStringExtra(currentImagePath));
if (requestCode == 100) {
//Get Capture Image
// Bitmap captureImage = (Bitmap) data.getExtras().get("data");
//Set Captue Image to ImageView
imageView.setImageBitmap(mBitmap);
// imageView.setImageBitmap(captureImage);
}
imageView.setImageBitmap(mBitmap); this line is not working so to say.
I am building a simple camera app in Android to show it in a imageView .I can get thumbnail which is very blurr .So I have a made file for that and then It gives me the location of the file. When I check it ,Its is of 0 kb which is well understood .
My Task is to capture image and save at mCurrentPhotoPath and I should be able to display it in my imageView in startActivityForResult()
But App Crashes Before Caling Before that again and again.
I know something is buggy in this line
Uri photoURI = FileProvider.getUriForFile(MainActivity.this,"com.infolabs.photu", photoFile);
.I have changed Uri photoURI = FileProvider.getUriForFile(this, "com.example.android.fileprovider",photoFile); to com.infolabs.photu .But I can't get whats wrong in it .
Please have a look at my code and I have location URL location but It won't show or work as the image is 0KB
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b = (Button) findViewById(R.id.captureimage);
imageView = (ImageView) findViewById(R.id.imageView);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null)
{
// Create the File where the photo should go
File photoFile = null;
try
{
photoFile = createImageFile();
Toast.makeText(MainActivity.this,mCurrentPhotoPath,Toast.LENGTH_LONG).show();
}
catch (IOException ex)
{
Toast.makeText(MainActivity.this,"the file is not created ",Toast.LENGTH_SHORT).show();
}
if (photoFile != null)
{
//this Uri does not working properly
Uri photoURI = FileProvider.getUriForFile(MainActivity.this,"com.infolabs.photu", photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
});
}
Error Log:-
FATAL EXCEPTION: main
Process: infolabs.photu, PID: 21415
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.XmlResourceParser android.content.pm.ProviderInfo.loadXmlMetaData(android.content.pm.PackageManager, java.lang.String)' on a null object reference
at android.support.v4.content.FileProvider.parsePathStrategy(FileProvider.java:583)
at android.support.v4.content.FileProvider.getPathStrategy(FileProvider.java:557)
at android.support.v4.content.FileProvider.getUriForFile(FileProvider.java:399)
at infolabs.photu.MainActivity$1.onClick(MainActivity.java:71)
at android.view.View.performClick(View.java:5269)
at android.view.View$PerformClick.run(View.java:21556)
at android.os.Handler.handleCallback(Handler.java:815)
at android.os.Handler.dispatchMessage(Handler.java:104)
at android.os.Looper.loop(Looper.java:207)
at android.app.ActivityThread.main(ActivityThread.java:5776)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)
04-17 16:56:15.085 21415-21425/infolabs.photu I/System: FinalizerDaemon: finalize objects = 65
Capture the image from Camera and save it to sdcard:
cameraBtn.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
try {
File f = createImageFile();//createImageFile() is added.
if (f != null) {
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
} catch (IOException IOE) {
IOE.printStackTrace();
}
}
});
private File createImageFile() throws IOException {
String imageFileName = "image";
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
imageFileName = imageFileName + timeStamp.toString();
File albumF = getStorageDir();
File imageF = File.createTempFile(imageFileName, ".jpg", albumF);
return imageF;
}
private File getStorageDir() {
File storageDir = null;
storageDir = new File(Environment.getExternalStorageDirectory(), "/MyApp" );
if (storageDir != null) {
if (!storageDir.mkdirs()) {
if (!storageDir.exists()) {
Log.d("CameraSample", "failed to create directory");
return null;
}
}
}
return storageDir;
}
private File getImageFile() {
String Path = Environment.getExternalStorageDirectory() + "/MyApp";
File f = new File(Path);
File imageFiles[] = f.listFiles();
if (imageFiles == null || imageFiles.length == 0) {
return null;
}
File lastModifiedFile = imageFiles[0];
for (int i = 1; i < imageFiles.length; i++) {
if (lastModifiedFile.lastModified() < imageFiles[i].lastModified()) {
lastModifiedFile = imageFiles[i];
}
}
return lastModifiedFile;
}
// overwrite the method from activity, read the save image file and show in the ImageView:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
File imageFile = getImageFile();
Bitmap bitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath());
mImageView.setImageBitmap(bitmap);
}}}
Add permission in the menifest file:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.CAMERA" />
Alternatively, you can try the Picasso library, it is very easy and will solve most of your problems relating to handling images.
You can find it here: http://square.github.io/picasso/
I am trying to update an image that is saved in parse through the android app, I am able o retrieve it and load it to the app but I am not able to save the new image that I selected to replace the old one. This is how I tried to do it and it only saves the file on the current state and not to parse. This is the code that I have currently and it is not working the way I want it to. Kindly assist.
Code is as follows
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == LOAD_IMAGE_RESULTS) {
Uri pickedImage = data.getData();
InputStream inputStream;
try {
inputStream = getContentResolver().openInputStream(pickedImage);
Bitmap selectedImages = BitmapFactory.decodeStream(inputStream);
imageSelected.setImageBitmap(selectedImages);
selectedImages = ((BitmapDrawable) imageSelected.getDrawable()).getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
selectedImages.compress(Bitmap.CompressFormat.PNG, 5, stream);
byte[] imageRec = stream.toByteArray();
file = new ParseFile("profileUpdate.png", imageRec);
file.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
if (null == e)
currentUser.put("ProfilePicture", file);
}
});
} catch (FileNotFoundException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Unable to load image",
Toast.LENGTH_LONG).show();
}
}
}
}
I just added the currentUser.saveInBackground(); line after currentUser.put("ProfilePicture", file); and added a currentUser.remove("ProfilePicture"); before it and it worked.
Ok guys, so after spending one day trying to figure out how to upload an image to parse servers i finally decided to ask for your help. I didn't find any full example on how to do this.
What i want to be able to do is:
select image from gallery (already did that)
load into inageView (already did that)
at onClick event upload the selected picture to Parse servers (my problem)
Here you have my code snippet so far, but it's not working.
private static int RESULT_LOAD_IMAGE = 1;
mSubmitJobBTN.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
createJob(); //this method will send data to Parse
}
});
private void addJob(final String mUsernameText, String mJobNameText,
String mJobDescriptionText, String mJobPriceText) {
/*Bitmap bitmap = BitmapFactory.decodeFile("picturePath");
// Convert it to byte
ByteArrayOutputStream stream = new ByteArrayOutputStream();
// Compress image to lower quality scale 1 - 100
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] image = stream.toByteArray();
try {
image = readInFile(path);
} catch (Exception e) {
e.printStackTrace();
}*/
ParseUser user = ParseUser.getCurrentUser();
anunt.put("username", "andrei");
anunt.put("jobName", mJobNameText);
anunt.put("jobDescription", mJobDescriptionText);
anunt.put("jobPrice", mJobPriceText);
/*// Create a column named "jobPicture" and set the string
anunt.put("jobPicture", "picturePath");
// Create the ParseFile
ParseFile file = new ParseFile("picturePath", image);
// Upload the image into Parse Cloud
file.saveInBackground();
// Create a column named "ImageFile" and insert the image
anunt.put("ImageFile", file);*/
anunt.saveInBackground(new SaveCallback() {
public void done(ParseException e) {
if (e == null) {
Toast.makeText(getApplicationContext(),
"Job succesfully posted!", Toast.LENGTH_LONG)
.show();
Intent in = new Intent(getApplicationContext(),
JobsListActivity.class);
in.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(in);
finish();
} else {
Toast.makeText(getApplicationContext(),
"Sign up error, please check all the fields",
Toast.LENGTH_LONG).show();
}
}
});
}
public byte[] readInFile(String path) throws IOException {
byte[] data = null;
File file = new File(path);
InputStream input_stream = new BufferedInputStream(new FileInputStream(
file));
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
data = new byte[16384]; // 16K
int bytes_read;
while ((bytes_read = input_stream.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, bytes_read);
}
input_stream.close();
return buffer.toByteArray();
}***strong text***
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK
&& null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
PreferenceManager.getDefaultSharedPreferences(this).edit()
.putString("picturePath", picturePath).commit();
cursor.close();
ImageView imageView = (ImageView) findViewById(R.id.addJob_imageView);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
You should use PHP or any server script to upload image from android to the server. Try the URL given below,
Upload Image to Server PHP Android
this is the answer!
ByteArrayOutputStream stream = new ByteArrayOutputStream();
// Compress image to lower quality scale 1 - 100
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] imagez = stream.toByteArray();
ParseFile filez = new ParseFile("androidbegin.png",
imagez);
filez.saveInBackground();
imgupload = new ParseObject("Anunturi");
imgupload.put("JobPictureName", "AndroidBegin Logo");
imgupload.put("jobPicture", filez);
imgupload.put("jobPictureName", picturePath);
imgupload.put("username", mUsernameText);
imgupload.put("jobName", mJobNameText);
imgupload.put("jobDescription", mJobDescriptionText);
imgupload.put("jobPrice", mJobPriceText);
imgupload.saveInBackground(new SaveCallback() {
public void done(ParseException e) {
if (e == null) {
Toast.makeText(getApplicationContext(),
"Job succesfully posted!",
Toast.LENGTH_LONG).show();
Intent in = new Intent(
getApplicationContext(),
JobsListActivity.class);
in.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(in);
finish();
} else {
mGoogleNow
.setVisibility(mGoogleNow.INVISIBLE);
Toast.makeText(getApplicationContext(),
"An error occured",
Toast.LENGTH_LONG).show();
}
}
});
} else {
bitmap = null;
imgupload = new ParseObject("Anunturi");
imgupload.put("username", mUsernameText);
imgupload.put("jobName", mJobNameText);
imgupload.put("jobDescription", mJobDescriptionText);
imgupload.put("jobPrice", mJobPriceText);
imgupload.put("jobPictureName", "null");
imgupload.saveInBackground(new SaveCallback() {
public void done(ParseException e) {
if (e == null) {
Toast.makeText(
getApplicationContext(),
"Job succesfully posted!",
Toast.LENGTH_LONG).show();
Intent in = new Intent(
getApplicationContext(),
JobsListActivity.class);
in.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(in);
finish();
} else {
Toast.makeText(
getApplicationContext(),
"Error while posting job...",
Toast.LENGTH_LONG).show();
}
}
});