So after trying many answers for the same question, here are just two e.g;
Saving an image in android
and
Saving an image to a server using a Java applet
My app still fails in fact whatever I have done has made it worse, before it would actually save the image as "temp.jpg" in the ExtSD root folder, now when I click the tick to accept the photo nothing happens, no crashing, no nothing, I can retake the image and I can cancel the taking of a photo but nothing else happens.
What it does now:
Opens the camera (or gallery)
Takes the photo
Fails to save/set the photo
What I want it to do;
Take the photo
Store it with a unique name (timestamp)
Have the image set to CircleView
Here is my code (if you need more please ask for what you need);
CircleImageView circleImageView;
ImageButton b;
private void selectImage() {
final CharSequence[] options = { "Take a Pic", "Choose from Gallery", "Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Set Profile Pic");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("Take a Pic"))
{
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
String folder_main = "iDealer";
String sub_folder = "ProPics";
String timeStamp = new SimpleDateFormat("ddMMyyy_HHmmss").format(Calendar.getInstance().getTime());
String pro_pic_name = folder_main + "_" + timeStamp;
File f = new File(android.os.Environment.getExternalStorageDirectory() + "/" + folder_main + "/" + sub_folder + pro_pic_name);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivityForResult(intent, 1);
}
else if (options[item].equals("Choose from Gallery"))
{
Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 2);
}
else if (options[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
File f = new File(Environment.getExternalStorageDirectory().toString());
for (File temp : f.listFiles()) {
if (temp.getName().equals("temp.jpg")) {
f = temp;
break;
}
}
try {
Bitmap bitmap;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),
bitmapOptions);
circleImageView.setImageBitmap(bitmap);
String path = android.os.Environment
.getExternalStorageDirectory()
+ File.separator
+ "iDealer" + File.separator + "default";
f.delete();
OutputStream outFile = null;
File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");
try {
outFile = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile);
outFile.flush();
outFile.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
} else if (requestCode == 2) {
Uri selectedImage = data.getData();
String[] filePath = { MediaStore.Images.Media.DATA };
Cursor c = getContentResolver().query(selectedImage,filePath, null, null, null);
if (c != null) {
c.moveToFirst();
}
int columnIndex = c.getColumnIndex(filePath[0]);
String picturePath = c.getString(columnIndex);
c.close();
Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
Log.w("path from gallery = ", picturePath+"");
circleImageView.setImageBitmap(thumbnail);
}
}
}
Related
I am trying to give a preview of PDF to the user before uploading it to a server. I am using PdfRenderer. I just to give the preview of the 1st page. On Start, I am calling the file chooser function that lets you select a pdf file from Internal memory, and on ActivityResult the render function is called, however, I am facing an error
I/System.out: Cursor= android.content.ContentResolver$CursorWrapperInner#a8d29d4
Uri String= content://com.adobe.scan.android.documents/document/root%3A23
File pathcontent://com.adobe.scan.android.documents/document/root%3A23
W/System.err: java.lang.IllegalArgumentException: Invalid page index
at android.graphics.pdf.PdfRenderer.throwIfPageNotInDocument(PdfRenderer.java:282)
at android.graphics.pdf.PdfRenderer.openPage(PdfRenderer.java:229)
at com.ay404.androidfileloaderreader.CustomFunc.Main2Activity.openPdfFromStorage(Main2Activity.java:56)
Here is my code:
#RequiresApi(api=Build.VERSION_CODES.LOLLIPOP)
private void openPdfFromStorage(Uri uri,String filename) throws IOException {
File fileCopy = new File(getCacheDir(), filename);//anything as the name
copyToCache(fileCopy, uri);
ParcelFileDescriptor fileDescriptor =
ParcelFileDescriptor.open(fileCopy,
ParcelFileDescriptor.MODE_READ_ONLY);
mPdfRenderer = new PdfRenderer(fileDescriptor);
mPdfPage = mPdfRenderer.openPage(1);
Bitmap bitmap = Bitmap.createBitmap(mPdfPage.getWidth(),
mPdfPage.getHeight(),
Bitmap.Config.ARGB_8888);//Not RGB, but ARGB
mPdfPage.render(bitmap, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);
imageView.setImageBitmap(bitmap);
}
void copyToCache(File file,Uri uri) throws IOException {
if (!file.exists()) {
InputStream input = getContentResolver().openInputStream(uri);
FileOutputStream output = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int size;
while ((size = input.read(buffer)) != -1) {
output.write(buffer, 0, size);
}
input.close();
output.close();
}
}
RequiresApi(api=Build.VERSION_CODES.LOLLIPOP)
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_PDF_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
filePath = data.getData();
Uri uri = data.getData();
String uriString=uri.toString();
File myFile=new File(uriString);
String displayName=null;
Cursor cursor=null;
Log.e("URI: ", uri.toString());
try {
if (uriString.startsWith("content://")) {
try {
cursor=getApplicationContext().getContentResolver().query(uri, null, null, null, null);
System.out.println("Cursor= " + cursor);
System.out.println("Uri String= " + uriString);
System.out.println("File path" + data.getData());
if (cursor != null && cursor.moveToFirst()) {
displayName=cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
openPdfFromStorage(uri,displayName);
File imgFile=new File(String.valueOf(data.getData()));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
cursor.close();
}
} else if (uriString.startsWith("file://")) {
System.out.println("Uri String= " + uriString);
System.out.println("File path" + myFile.getAbsolutePath());
displayName=myFile.getName();
try {
openPdfFromStorage(uri,displayName);
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
private void fileChoser(){
Intent intent=new Intent();
intent.setType("application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Pdf"), PICK_PDF_REQUEST);
}
#Override
protected void onStart() {
super.onStart();
fileChoser();
}
}
Found the fix, the path needs to be static, therefore, I am copying the files to cache and then opening them from cache location
private void showPdf(String base64, String filename) {
String fileName = "test_pdf ";
try {
final File dwldsPath = new File(this.getExternalFilesDir(String.valueOf(this.getCacheDir()))+"/"+filename);
Log.d("File path", String.valueOf(dwldsPath));
byte[] pdfAsBytes = Base64.decode(base64, 0);
FileOutputStream os;
os = new FileOutputStream(dwldsPath, false);
os.write(pdfAsBytes);
os.flush();
os.close();
Uri uri = FileProvider.getUriForFile(this,
BuildConfig.APPLICATION_ID + ".provider",
dwldsPath);
fileName="";
String mime = this.getContentResolver().getType(uri);
openPDF(String.valueOf(dwldsPath),fileName);
} catch(Exception e){
e.printStackTrace();
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_SHORT).show();
}
}
My first question would be, Is onCreate method needed on every new class in android ?
Next, can we use multiple onActivityResult method without causing distortion
?
For exemple my MainActivity and ShareActivity class both have their own onActivityResult and Oncreate method (code taken from git)
MainActivity is for opening camera and gallery
ShareActivity is for sharing images captured
Note : Both class check for permission first
I wanna call the ShareActivity in my MainActivity, the logical thing to do would be
share.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent myIntent = new Intent(MainActivity.this, ShareActivity.class);
startActivity(myIntent);
}
});
But my ShareActivity also has this
#OnClick(R.id.open_share)
void onShareTouched() {
boolean has_perms = EasyPermissions.hasPermissions(ShareActivity.this, perms);
if (has_perms) {
shareImageFromBitmap(this.bmp);
} else {
EasyPermissions.requestPermissions(
ShareActivity.this,
getString(R.string.rationale_storage),
SHARE_STORAGE_PERMS_REQUEST_CODE,
perms);
}
}
And then I thought about calling it like this
ShareActivity.getInstance().onShareTouched();
But the app keep crashing, everytime I call the Share class,
Edit : Should I use implement ?
Note :the Share class works fine without MainActivity (I tried in new project)
for better understanding I leave the complete code below
ShareActivity
public class ShareActivity extends AppCompatActivity {
private static ShareActivity instance;
private static final String TAG = "ShareActivity";
private final int SHARE_STORAGE_PERMS_REQUEST_CODE = 900;
private final int RESULT_LOAD_IMG_REQUEST_CODE = 778;
private final String[] perms = { android.Manifest.permission.WRITE_EXTERNAL_STORAGE, android.Manifest.permission.READ_EXTERNAL_STORAGE};
private static final String IMAGE_URL = null;
private Bitmap bmp;
#BindView(R.id.open_share)
SimpleDraweeView imageView2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
bmp = getBitmapFromUrl(IMAGE_URL);
imageView2.setImageURI(Uri.parse(IMAGE_URL));
instance = this;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == RESULT_LOAD_IMG_REQUEST_CODE && resultCode == RESULT_OK) {
List<Image> images = ImagePicker.getImages(data);
if(images.size() > 0) {
String imagePath = images.get(0).getPath();
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
bmp = BitmapFactory.decodeFile(imagePath, options);
imageView2.setImageURI(Uri.fromFile(new File(imagePath)));
}
}
}
#OnClick(R.id.open_share)
void onShareTouched() {
boolean has_perms = EasyPermissions.hasPermissions(ShareActivity.this, perms);
if (has_perms) {
shareImageFromBitmap(this.bmp);
} else {
EasyPermissions.requestPermissions(
ShareActivity.this,
getString(R.string.rationale_storage),
SHARE_STORAGE_PERMS_REQUEST_CODE,
perms);
}
}
#AfterPermissionGranted(SHARE_STORAGE_PERMS_REQUEST_CODE)
private void shareImageFromBitmap(Bitmap bmp) {
Uri uri = getUriImageFromBitmap(bmp, ShareActivity.this);
if(uri == null) {
//Show no URI message
return;
}
final Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_TEXT, IMAGE_URL);
shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
shareIntent.setType("image/png");
shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(Intent.createChooser(shareIntent, "Share image using"));
}
private Bitmap getBitmapFromUrl(String url) {
Uri uri = Uri.parse(url);
ImageRequest downloadRequest = ImageRequest.fromUri(uri);
CacheKey cacheKey = DefaultCacheKeyFactory.getInstance().getEncodedCacheKey(downloadRequest, ShareActivity.this);
if (ImagePipelineFactory.getInstance().getMainFileCache().hasKey(cacheKey)) {
BinaryResource resource = ImagePipelineFactory.getInstance().getMainFileCache().getResource(cacheKey);
byte[] data = null;
try {
data = resource.read();
} catch (IOException e) {
e.printStackTrace();
}
return BitmapFactory.decodeByteArray(data, 0, data.length);
}
return null;
}
private Uri getUriImageFromBitmap(Bitmap bmp, Context context) {
if(bmp == null)
return null;
Uri bmpUri = null;
try {
File file = new File(context.getExternalFilesDir(Environment.DIRECTORY_PICTURES), "IMG_" + System.currentTimeMillis() + ".png");
FileOutputStream out = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.PNG, 90, out);
out.flush();
out.close();
bmpUri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".provider", file);
} catch (IOException e) {
e.printStackTrace();
}
return bmpUri;
}
public static ShareActivity getInstance() {
return instance;
}
}
MainActivity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK && data != null) {
if (requestCode == OPEN_THING) {
Uri uri = Objects.requireNonNull(data.getExtras()).getParcelable(ScanConstants.SCANNED_RESULT);
Bitmap bitmap;
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
if (uri != null) {
getContentResolver().delete(uri, null, null);
}
scannedImageView.setImageBitmap(bitmap);
FileOutputStream outputStream = null;
File sdCard = Environment.getExternalStorageDirectory();
File directory = new File(sdCard.getAbsolutePath() + "/Scan Documents");
directory.mkdir();
String filename = String.format("d.jpg", System.currentTimeMillis());
File outFile = new File(directory, filename);
Toast.makeText(this, "Image Saved Successfully", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
intent.setData(Uri.fromFile(outFile));
sendBroadcast(intent);
try {
outputStream = new FileOutputStream(outFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
outputStream.flush();
outputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
I found a better easier way
I had to completely change my method, I put everything in my button onClick
share.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Drawable myDrawable = scannedImageView.getDrawable();
Bitmap bitmap = ((BitmapDrawable)myDrawable).getBitmap();
try{
File file = new File(MainActivity.this.getExternalCacheDir(), "myImage.png");
FileOutputStream fOut = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 80, fOut);
fOut.flush();
fOut.close();
file.setReadable(true, false);
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
intent.setType("image/png");
startActivity(Intent.createChooser(intent, "Share Image Via"));
}catch (FileNotFoundException e){
e.printStackTrace();
Toast.makeText(MainActivity.this, "File not found", Toast.LENGTH_SHORT).show();
}catch (IOException e){
e.printStackTrace();
}catch (Exception e){
e.printStackTrace();
}
}
});
No need ShareActivity it works great
I have a problem with Uri object. User should take a photo and next this is sending to Firebase Storage. But sth is wrong with onActivityResult.
I read a lot of topics (https://developer.android.com/training/camera/photobasics.html, StackOverFlow too) but nothing works with this code.
There is an error:
Attempt to invoke virtual method 'java.lang.String android.net.Uri.getLastPathSegment()' on a null object reference
Below is a code:
mUploadBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(intent, CAMERA_REQUEST_CODE);
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == CAMERA_REQUEST_CODE && resultCode == RESULT_OK && data != null) {
mProgress.setMessage("Uploading Image...");
mProgress.show();
Uri uri = data.getData();
StorageReference filepath = mStorage.child("Photos").child(uri.getLastPathSegment());
filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
mProgress.dismiss();
Uri downloadUri = taskSnapshot.getDownloadUrl();
Picasso.with(MainActivity.this).load(downloadUri).fit().centerCrop().into(mImageView);
Toast.makeText(MainActivity.this, "Upload Done.", Toast.LENGTH_LONG).show();
}
});
}
}
}
As I checked, data (Intent) in onActivityResult is equal to NULL, so uri is null as well.
So, how can I resolve this challenge and make it usable? Should I use a Bitmap to have an access to a photo?
Could someone help me to resolve this situation?
Regards
I figured out with my question.
It works at now.
private ProgressDialog mProgress;
private Button mUploadBtn;
private ImageView mImageView;
Uri picUri;
private StorageReference mStorage;
private static final int CAMERA_REQUEST_CODE = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mStorage = FirebaseStorage.getInstance().getReference();
mUploadBtn = (Button) findViewById(R.id.uploadBtn);
mImageView = (ImageView) findViewById(R.id.imageView);
mProgress = new ProgressDialog(this);
mUploadBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
File file=getOutputMediaFile(1);
picUri = Uri.fromFile(file); // create
i.putExtra(MediaStore.EXTRA_OUTPUT,picUri); // set the image file
startActivityForResult(i, CAMERA_REQUEST_CODE);
}
});
}
/** Create a File for saving an image */
private File getOutputMediaFile(int type){
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "MyApplication");
/**Create the storage directory if it does not exist*/
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
return null;
}
}
/**Create a media file name*/
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
if (type == 1){
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"IMG_"+ timeStamp + ".png");
} else {
return null;
}
return mediaFile;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == CAMERA_REQUEST_CODE && resultCode == RESULT_OK ) {
mProgress.setMessage("Uploading Image...");
mProgress.show();
Uri uri = picUri;
StorageReference filepath = mStorage.child("Photos").child(uri.getLastPathSegment());
filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
mProgress.dismiss();
Uri downloadUri = taskSnapshot.getDownloadUrl();
Picasso.with(MainActivity.this).load(downloadUri).fit().centerCrop().into(mImageView);
Toast.makeText(MainActivity.this, "Upload Done.", Toast.LENGTH_LONG).show();
}
});
}
}
Always create your file and store the captured image using the path as follows
File photoFile = null;
mUploadBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (intent.resolveActivity(getPackageManager()) != null) {
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
ex.printStackTrace();
}
// Continue only if the File was successfully created
if (photoFile != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
startActivityForResult(takePictureIntent, CAMERA_REQUEST_CODE);
}
}
});
}
private File createImageFile() throws IOException {
// Create an image mSelectedFile name
String timeStamp = new SimpleDateFormat(Constants.PHOTO_DATE_FORMAT, Locale.ENGLISH).format(new Date());
String imageFileName = "IMG_" + timeStamp;
File storageDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File file = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
return file;
}
Then use this file "photoFile" and use it as needed in onActivityResult.
I faced the same problem before so i made sure that i check everything i can check when onActivityResult is called below is my code.
First i use this intent to capture image
File photoFile;
URI uri;
mUploadBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePhotoIntent.resolveActivity(getPackageManager()) != null)
{
try
{
photoFile = Create_ImageFile();
}
catch (Exception e)
{
Log.e("file", e.toString());
}
if (photoFile != null)
{
takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile.getAbsoluteFile()));
}
}
startActivityForResult(takePhotoIntent, CAMERA_REQUEST_CODE);
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent)
{
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch (requestCode) {
case CAMERA_REQUEST_CODE:
if (resultCode == Activity.RESULT_OK)
{
try
{
Uri selectedImageURI = null;
ByteArrayOutputStream bos;
Bitmap bitmap = null;
int orientation;
ExifInterface exif = null;
FileOutputStream fos = null;
bos = new ByteArrayOutputStream();
try
{
uri=imageReturnedIntent.getData();
selectedImageURI = imageReturnedIntent.getData();
bitmap= BitmapFactory.decodeFile(GetRealPathFromURI(selectedImageURI));
exif = new ExifInterface(GetRealPathFromURI(selectedImageURI));
fos = new FileOutputStream(GetRealPathFromURI(selectedImageURI));
}
catch (Exception e)
{
e.printStackTrace();
}
if(bitmap==null)
{
uri=Uri.fromFile(photoFile.getAbsoluteFile()));
bitmap=BitmapFactory.decodeFile(photoFile.getAbsolutePath());
exif = new ExifInterface(photoFile.getAbsolutePath());
fos = new FileOutputStream(photoFile.getAbsolutePath());
}
if(bitmap==null)
{
String imagePath = getPathGalleryImage(imageReturnedIntent);
bitmap = BitmapFactory.decodeFile(imagePath);
exif = new ExifInterface(imagePath);
fos = new FileOutputStream(imagePath);
}
Log.e("PhotoFile",photoFile.getAbsolutePath());
// Bitmap bitmap =(Bitmap) imageReturnedIntent.getExtras().get("data");
//bitmap = Bitmap.createScaledBitmap(bitmap,bitmap.getWidth(),bitmap.getHeight(), false);
orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1);
Log.e("ExifInteface .........", "rotation ="+orientation);
//exif.setAttribute(ExifInterface.ORIENTATION_ROTATE_90, 90);
Log.e("orientation", "" + orientation);
Matrix m = new Matrix();
if ((orientation == ExifInterface.ORIENTATION_ROTATE_180)) {
m.postRotate(180);
//m.postScale((float) bm.getWidth(), (float) bm.getHeight());
// if(m.preRotate(90)){
Log.e("in orientation", "" + orientation);
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),bitmap.getHeight(), m, true);
} else if (orientation == ExifInterface.ORIENTATION_ROTATE_90) {
m.postRotate(90);
Log.e("in orientation", "" + orientation);
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),bitmap.getHeight(), m, true);
}
else if (orientation == ExifInterface.ORIENTATION_ROTATE_270)
{
m.postRotate(270);
Log.e("in orientation", "" + orientation);
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),bitmap.getHeight(), m, true);
}
else
{
m.postRotate(0);
Log.e("in orientation", "" + orientation);
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),bitmap.getHeight(), m, true);
}
//CropImage.activity(selectedImageURI).setGuidelines(CropImageView.Guidelines.ON).start(this);
bitmap.compress(Bitmap.CompressFormat.JPEG, 80, bos);
userProfileIMG.setImageBitmap(bitmap);
StorageReference filepath = mStorage.child("Photos").child(uri.getLastPathSegment());
}
catch (Exception e)
{
e.printStackTrace();
}
}
break;
}
}
private String getPathGalleryImage(Intent imageURI)
{
Uri selectedImage = imageURI.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 imagePath = cursor.getString(columnIndex);
cursor.close();
return imagePath;
}
/**
* When image is returned we get its real path
**/
private String GetRealPathFromURI(Uri contentURI)
{
String result;
Cursor cursor = getContentResolver().query(contentURI, null, null, null, null);
if (cursor == null) {
// Source is Dropbox or other similar local file path
result = contentURI.getPath();
} else {
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
result = cursor.getString(idx);
cursor.close();
}
return result;
}
private File Create_ImageFile() throws IOException
{
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
String imageFileName = "JPEG_" + timeStamp;
File mediaStorageDir = getApplicationContext().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = new File(mediaStorageDir.getAbsolutePath() + File.separator + imageFileName);
return image;
}
after this process i always ended having a bitmap to use it as i want.
For Get Actual Image predefined path of Captured Image using
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
this.startActivityForResult(cameraIntent, 101);
After Captured Image you can get Captured Image on path which is set in cameraIntent. If you don't Want to set predefined path then check Intent data.
if (resultCode == android.app.Activity.RESULT_OK && requestCode == 101) {
try {
path_mm = "Onsuccess_resultcode";
generateNoteOnSD("photo34.txt", path_mm);
Bitmap photo = null;
if (data == null) {
//get Bitmap here.
}
else {
Uri u1 = data.getData();
//get uri and find actual path on that uri.
}
}catch(Exception ex)
{}}
I pick the image from gallery and tried to save the image in my internal storage.
The file is saved but it looks damaged. It is not showing the image.
Can I know what I have to do now?
Here is image I got:
public class ImageUpload extends android.app.Fragment
{
ImageView image;
String img_str;
Button upload;
Bitmap finalBitmap;
private static final int CONTENT_REQUEST=1337;
private File output=null;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable final ViewGroup container, #Nullable Bundle savedInstanceState) {
View v=inflater.inflate(R.layout.activity_imageupload,container,false);
image=(ImageView)v.findViewById(R.id.image);
upload=(Button)v.findViewById(R.id.upload);
/* Bitmap bitmap = image.getDrawingCache();*/
image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent();
i.setAction(Intent.ACTION_PICK);
i.setType("image/*");
i.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(
Intent.createChooser(i, "Select Picture"), 1);
save Image();
}
});
image.buildDrawingCache();
finalBitmap = image.getDrawingCache();
return v;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if (resultCode == MainActivity.RESULT_OK) {
if (requestCode == 1) {
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
System.out.println("Image Path : " + selectedImagePath);
image.setImageURI(selectedImageUri);
image.setDrawingCacheEnabled(true);
}
else if (requestCode == CONTENT_REQUEST) {
if (resultCode == 1337) {
Intent i=new Intent(Intent.ACTION_VIEW);
i.setDataAndType(Uri.fromFile(output), "image/jpeg");
startActivity(i);
getActivity().finish();
}
}
}
super.onActivityResult(requestCode, resultCode, data);
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = getActivity().getContentResolver().query(uri,
projection, null, null, null);
if (cursor == null)
return null;
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String s = cursor.getString(column_index);
cursor.close();
return s;
}
public String image() {
image.buildDrawingCache();
finalBitmap = image.getDrawingCache();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
finalBitmap.compress(Bitmap.CompressFormat.PNG, 90, stream);
byte[] image = stream.toByteArray();
System.out.println("byte array:" + image);
img_str = Base64.encodeToString(image, 0);
Toast.makeText(getActivity(), img_str, Toast.LENGTH_LONG).show();
System.out.println("string:" + img_str);
return null;
}
private void save Image() {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/hello_images");
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Image-"+ n +".jpg";
File file = new File (myDir, fname);
if (file.exists ()) file.delete ();
try {
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}`
Add this code in OnActivityResult
Bitmap bmp = BitmapFactory.decodeFile(image_path);
thumb.setImageBitmap(bmp);
saveImageFile(bmp);
Save Bitmap to sdcard Method
public String saveImageFile(Bitmap bitmap) {
FileOutputStream out = null;
String filename = getFilename();
try {
out = new FileOutputStream(filename);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return filename;
}
private String getFilename() {
File file = new File(Environment.getExternalStorageDirectory()
.getPath(), "TestFolder");
if (!file.exists()) {
file.mkdirs();
}
String uriSting = (file.getAbsolutePath() + "/"
+ System.currentTimeMillis() + ".jpg");
return uriSting;
}
You are calling the saveImage function even before the finalBitmap variable has any value, If you call the below function when you click the ImageView with it's drawing cache, It could work ( adjust the path as required).
public File WriteBmpToFile(Bitmap bmp) {
String file_path = Environment.getExternalStorageDirectory().getAbsolutePath() +
"/.kyc";
File dir = new File(file_path);
if (!dir.exists())
dir.mkdirs();
File file = new File(dir, "kyc_" + Calendar.getInstance().getTimeInMillis() + ".jpg");
FileOutputStream fOut = null;
try {
fOut = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.JPEG, 85, fOut);
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
try {
fOut.flush();
fOut.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return file;
}
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();
}
}
});