remove "Select image from gallery" option when app starts. Android - android

I am a newbie to android.I tried working on an app using some open source code.
The app uses image from gallery and then it is taken into and imageview and we do some operations on the image.
What i need is, the app should start with some default image already into the imageview..then i will add some button to select image from gallery later. I couldnot understand the work flow here. It would be greateful If someone could guide me.
Here is my code main activity.which also contains splash screen.
public class Main extends Activity {
static final String PREFS_FILE = "image_edit";
/** The URI of the Image to display. */
private int _wait;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.main_screen);
_wait = 1000;
imageUri = null;
}
#Override
protected void onResume() {
super.onResume();
if (_wait != 0) {
new CountDownTimer(_wait, _wait) {
#Override
public void onFinish() {
if (imageUri != null) {
Intent viewActivity = new Intent(Main.this, Viewer.class);
viewActivity.putExtra("image", imageUri);
startActivity(viewActivity);
} else {
startActivityForResult(newIntent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI),0);
}
}
#Override
public void onTick(long millisUntilFinished) {
}
}.start();
_wait = 0;
} else {
if (imageUri != null) {
Intent viewActivity = new Intent(this, Viewer.class);
viewActivity.putExtra("image", imageUri);
startActivity(viewActivity);
} else {
startActivityForResult(newIntent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI), 0);
}
}
}
#Override
protected void onPause() {
super.onPause();
imageUri = null;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
imageUri = data.getData();
} else {
System.exit(0);
Log.e("result", "BAD");
}
}
}
Then from here the image taken goes to next activity called Viewer activity whose onresume is this
protected void onResume() {
super.onResume();
mHandler = new Handler();
mPreferences = this.getSharedPreferences(Main.PREFS_FILE, 0);
setContentView(R.layout.nothing);
// Inflate all the views.
int orientation = getResources().getConfiguration().orientation;
basicInit(orientation);
if (orientation == Configuration.ORIENTATION_PORTRAIT) {
initPortrait();
} else {
initLandscape();
}
Intent intent = getIntent();
Uri imageURI = null;
Log.e("URI:", intent.getData() + "");
if (intent.getAction() != null && intent.getAction().equals(Intent.ACTION_SEND)) {
Bundle extras = intent.getExtras();
if (extras.containsKey(Intent.EXTRA_STREAM)) {
imageURI = (Uri) extras.getParcelable(Intent.EXTRA_STREAM);
}
} else if (intent.getAction() != null && intent.getAction().equals(Intent.ACTION_VIEW)) {
imageURI = intent.getData();
} else {
imageURI = (Uri) intent.getParcelableExtra("image");
}
addImage(imageURI);
addDraggableImages();
_updateImageTask = new UpdateImage(mRelative, mHandler);
}
So i tried doing this in main view where the
if(wait !=0){}
else{
startActivity(new Intent(Main.this, Viewer.class));
}
but this does not work..error is runtimeexception
So It would be Helpful if somebody guided me..Thanks

As you can see in onResume() method of your MainActivity first it will go to the else part i.e startActivityForResult that will open up a gallery and ask you to pick up an image.
Instead of putting this into onResume,you can simple create a button in main_screen.xml
and then implement this functionality in onclickListener of that button.
To see an image by default,in the Imageview tag of your xml you can put this: android:src="#drawable/imageFile"
Does it make sense to you?

Below is given Java class and laoyout file similar to app that you are talking about.
MainActivity.java
package com.tag.photocaptureandgallery;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.MediaStore.MediaColumns;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
public class MainActivity extends Activity {
private final int SELECT_FILE = 1;
private final int REQUEST_CAMERA = 0;
private ImageView ivImage;
private Button btnSetImage;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ivImage = (ImageView) findViewById(R.id.ivImage);
btnSetImage = (Button) findViewById(R.id.btnSelectPhoto);
btnSetImage.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
}
});
}
private void selectImage() {
final CharSequence[] items = { "Take Photo", "Choose from Library",
"Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Add Photo!");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (items[item].equals("Take Photo")) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(android.os.Environment
.getExternalStorageDirectory(), "temp.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivityForResult(intent, REQUEST_CAMERA);
} else if (items[item].equals("Choose from Library")) {
Intent intent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
startActivityForResult(
Intent.createChooser(intent, "Select File"),
SELECT_FILE);
} else if (items[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 == REQUEST_CAMERA) {
File f = new File(Environment.getExternalStorageDirectory()
.toString());
for (File temp : f.listFiles()) {
if (temp.getName().equals("temp.jpg")) {
f = temp;
break;
}
}
try {
Bitmap bm;
BitmapFactory.Options btmapOptions = new BitmapFactory.Options();
bm = BitmapFactory.decodeFile(f.getAbsolutePath(),
btmapOptions);
// bm = Bitmap.createScaledBitmap(bm, 70, 70, true);
ivImage.setImageBitmap(bm);
String path = android.os.Environment
.getExternalStorageDirectory()
+ File.separator
+ "Phoenix" + File.separator + "default";
f.delete();
OutputStream fOut = null;
File file = new File(path, String.valueOf(System
.currentTimeMillis()) + ".jpg");
try {
fOut = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.JPEG, 85, fOut);
fOut.flush();
fOut.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
} else if (requestCode == SELECT_FILE) {
Uri selectedImageUri = data.getData();
String tempPath = getPath(selectedImageUri, MainActivity.this);
Bitmap bm;
BitmapFactory.Options btmapOptions = new BitmapFactory.Options();
bm = BitmapFactory.decodeFile(tempPath, btmapOptions);
ivImage.setImageBitmap(bm);
}
}
}
public String getPath(Uri uri, Activity activity) {
String[] projection = { MediaColumns.DATA };
Cursor cursor = activity
.managedQuery(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
}
Main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="10dp" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:padding="5dp" >
<Button
android:id="#+id/btnSelectPhoto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Select Photo" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="10dp" >
<ImageView
android:id="#+id/ivImage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:src="#drawable/ic_launcher" />
</LinearLayout>
</LinearLayout>
Also add necessary permissions for using Camera.

Related

How to select an image from the gallery and convert it to Base64? [duplicate]

sorry for asking silly question.but it solved yet my me.please help i had tried all codes on stackoverflow and follow other tutorial but it wont help at all.i am taking image from galary and convert to base64 it works perfectly fine when taking image on camera but why it dont work on galary i dont know please help me.;(
This is the code to select the image
private void selectImage() {
final CharSequence[] items = { "Take Photo", "Choose from Library",
"Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(TestFragment.this);
builder.setTitle("Add Photo!");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
boolean result= Utility.checkPermission(TestFragment.this);
if (items[item].equals("Take Photo")) {
userChoosenTask ="Take Photo";
if(result)
cameraIntent();
} else if (items[item].equals("Choose from Library")) {
userChoosenTask ="Choose from Library";
if(result)
galleryIntent();
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
After this
private void galleryIntent()
{
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);//
startActivityForResult(Intent.createChooser(intent, "Select File"),SELECT_FILE);
}
private void cameraIntent()
{
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == SELECT_FILE)
onSelectFromGalleryResult(data);
else if (requestCode == REQUEST_CAMERA)
onCaptureImageResult(data);
}
}
private void onCaptureImageResult(Intent data) {
bitmap = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
File destination = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + ".jpg");
FileOutputStream fo;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytes.toByteArray());
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
imgvcomp.setImageBitmap(bitmap);
String img=getStringImage(bitmap);
Log.v(TAG,"base64"+img);//perfectly string base64 to image
}
#SuppressWarnings("deprecation")
private void onSelectFromGalleryResult(Intent data) {
if (data != null) {
try {
bitmap = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), data.getData());
} catch (IOException e) {
e.printStackTrace();
}
}
imgvcomp.setImageBitmap(bitmap);
String img=getStringImage(bitmap);
Log.v(TAG,"base64"+img);//checking in log base64 string to image cropeed image found
}
public String getStringImage(Bitmap bmp){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 90, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}
private void showToastMessage(String message) {
Log.v(TAG, String.format("showToastMessage :: message = %s", message));
// Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
}
why i found the cropped image after selecting from galary?there is no error in error log here is the logcat
E/DynamiteModule: Failed to load module descriptor class: Didn't find class "com.google.android.gms.dynamite.descriptors.com.google.firebase.auth.ModuleDescriptor" on path: DexPathList[[zip file "/data/app/
W/FlurryAgent: Flurry session paused for
1 and remote module com.google.android.gms.tagmanager:8
Selected remote version of com.google.android.gms.tagmanager, version >= 8
No container asset found in /assets/containers. Checking top level /assets directory for container assets.
Tag Manager's event handler WILL NOT be installed (no container loaded)
Tag Manager initilization took 274ms
Using measurement service
Connecting to remote service
Connected to remote service
Processing queued up service tasks: 1
Suspending all threads took: 25.809ms
V/help: /9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAMCAgMCAgMDAwMEAwMEBQgFBQQEBQoHBwYIDAoMDAsK
CwsNDhIQDQ4RDgsLEBYQERMUFRUVDA8XGBYUGBIUFRT/2wBDAQMEBAUEBQkFBQkUDQsNFBQUFBQU
FBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBT/wAARCAzABywDASIA
AhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQA
AAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3
ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWm
p6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2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XA65
71NCrLHuZg4PTAwa0aTVirkDWmVZWwyk4YDgH0qSG1YMwABXgjB5pFkjZ2bac9xg4/z704XRi3Lg
IHGBnr/k09e5LaW4pzIiZGfLGBzyoJpl45KZTBxwPQU2FzudASQuC2Rz7Zp5k3KQRhuoI5x+Hf61
SbWotCrAgU9CWYjdj09frUj7SxC8gc5PAxTgSyZiwc8ZHYd+aTeEZ14IYck9DU66u5peysRhQ4Ib
DEEEsOBSM6BgYyCoHDDpT/3bxN8uQOoPQ/UVHDEuWAOGPTA6UyGk9GPExAJRNzEjO
You can use following code:
public static String encodeTobase64(Bitmap image) {
Bitmap immagex=image;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
immagex.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] b = baos.toByteArray();
String imageEncoded = Base64.encodeToString(b,Base64.DEFAULT);
Log.e("LOOK", imageEncoded);
return imageEncoded;
}
Use below code in onActivityResult()
InputStream imageStream = null;
try {
imageStream = this.getContentResolver().openInputStream(selectedImage);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Bitmap yourSelectedImage = BitmapFactory.decodeStream(imageStream);
encodeTobase64(yourSelectedImage);
Try this...
public String getStringImage(Bitmap bmp){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}
Here is a similar code. I have implemented the same thing in my app. You can select images from either gallery or camera and You can convert it as a base 64. Try this Its working for me. Hope it work for you too
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Base64;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import in.invis.organickerala.utilities.CropOption;
import in.invis.organickerala.R;
public class Profile_Activity extends AppCompatActivity {
private static final int PICK_FROM_CAMERA = 1;
private static final int CROP_FROM_CAMERA = 2;
private static final int PICK_FROM_FILE = 3;
final String[] items = new String[]{"Take From Camera", "Select From Gallery"};
ImageView picture;
AlertDialog.Builder builder;
ArrayAdapter<String> adapter;
private AccountManager mAccountManager;
private int PICK_IMAGE_REQUEST = 1;
private SharedPreferences mPreferences, myPrefs;
private SharedPreferences.Editor myPrefsEdit;
private Uri mImageCaptureUri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
adapter = new ArrayAdapter<String>(this, android.R.layout.select_dialog_item, items);
builder = new AlertDialog.Builder(this);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
// Show the Up button in the action bar.
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setTitle("Profile");
}
// Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
// setSupportActionBar(toolbar);
// getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mPreferences = getSharedPreferences("CurrentUser", MODE_PRIVATE);
myPrefs = getSharedPreferences("URI", MODE_PRIVATE);
myPrefsEdit = myPrefs.edit();
picture = (ImageView) findViewById(R.id.picture);
picture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
builder.setTitle("Select Image");
builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) { //pick from camera
if (item == 0) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
mImageCaptureUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(),
"tmp_avatar_" + String.valueOf(System.currentTimeMillis()) + ".jpg"));
intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
try {
intent.putExtra("return-data", true);
startActivityForResult(intent, PICK_FROM_CAMERA);
} catch (ActivityNotFoundException e) {
e.printStackTrace();
}
} else { //pick from file
Intent intent = new Intent();
intent.setType("Image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Complete action using"), PICK_FROM_FILE);
}
}
});
final AlertDialog dialog = builder.create();
picture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.show();
}
});
//END CAMERA STUFF
}// End OnCreate
});
String temp = myPrefs.getString("url", "defaultString");
try {
byte[] encodeByte = Base64.decode(temp, Base64.DEFAULT);
Bitmap bitmap = BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
picture.setImageBitmap(bitmap);
} catch (Exception e) {
e.getMessage();
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case PICK_FROM_CAMERA:
doCrop();
break;
case PICK_FROM_FILE:
mImageCaptureUri = data.getData();
doCrop();
break;
case CROP_FROM_CAMERA:
Bundle extras = data.getExtras();
if (extras != null) {
Bitmap photo = extras.getParcelable("data");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] b = baos.toByteArray();
String temp = Base64.encodeToString(b, Base64.DEFAULT);
myPrefsEdit.putString("url", temp);
myPrefsEdit.commit();
picture.setImageBitmap(photo);
}
File f = new File(mImageCaptureUri.getPath());
if (f.exists()) f.delete();
break;
}
}
private void doCrop() {
final ArrayList<CropOption> cropOptions = new ArrayList<CropOption>();
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setType("Image/*");
List<ResolveInfo> list = getPackageManager().queryIntentActivities(intent, 0);
int size = list.size();
if (size == 0) {
Toast.makeText(this, "Can not find Image crop app", Toast.LENGTH_SHORT).show();
return;
} else {
intent.setData(mImageCaptureUri);
intent.putExtra("outputX", 300);
intent.putExtra("outputY", 300);
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("scale", true);
intent.putExtra("return-data", true);
if (size != 0) {
Intent i = new Intent(intent);
ResolveInfo res = list.get(0);
i.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
startActivityForResult(i, CROP_FROM_CAMERA);
}
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// handle arrow click here
if (item.getItemId() == android.R.id.home) {
Intent intent = new Intent(Profile_Activity.this,MainActivity.class);
startActivity(intent);
}
return super.onOptionsItemSelected(item);
}
}
This is how I do it on my onActivityResult of my gallery intent.
String imagePath = ImageUtil.getRealPathFromURI(getActivity(), data.getData());
Then converting the whole thing to bitmap.
Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
Here is my getRealPathFromURI method from ImageUtil Class.
public static String getRealPathFromURI(Context context, Uri contentURI) {
String result = null;
String[] projection = {MediaStore.Images.Media.DATA};
try {
Cursor cursor = context.getContentResolver().query(contentURI, projection, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(projection[0]);
result = cursor.getString(columnIndex);
cursor.close();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
And here is my conversion from bitmap to base64.
public static String getBase64(Bitmap bitmap) {
if (bitmap != null) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
return Base64.encodeToString(baos.toByteArray(), Base64.DEFAULT);
}
return null;
}

Take image from gallery and convert to base64 issue

sorry for asking silly question.but it solved yet my me.please help i had tried all codes on stackoverflow and follow other tutorial but it wont help at all.i am taking image from galary and convert to base64 it works perfectly fine when taking image on camera but why it dont work on galary i dont know please help me.;(
This is the code to select the image
private void selectImage() {
final CharSequence[] items = { "Take Photo", "Choose from Library",
"Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(TestFragment.this);
builder.setTitle("Add Photo!");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
boolean result= Utility.checkPermission(TestFragment.this);
if (items[item].equals("Take Photo")) {
userChoosenTask ="Take Photo";
if(result)
cameraIntent();
} else if (items[item].equals("Choose from Library")) {
userChoosenTask ="Choose from Library";
if(result)
galleryIntent();
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
After this
private void galleryIntent()
{
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);//
startActivityForResult(Intent.createChooser(intent, "Select File"),SELECT_FILE);
}
private void cameraIntent()
{
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == SELECT_FILE)
onSelectFromGalleryResult(data);
else if (requestCode == REQUEST_CAMERA)
onCaptureImageResult(data);
}
}
private void onCaptureImageResult(Intent data) {
bitmap = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
File destination = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + ".jpg");
FileOutputStream fo;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytes.toByteArray());
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
imgvcomp.setImageBitmap(bitmap);
String img=getStringImage(bitmap);
Log.v(TAG,"base64"+img);//perfectly string base64 to image
}
#SuppressWarnings("deprecation")
private void onSelectFromGalleryResult(Intent data) {
if (data != null) {
try {
bitmap = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), data.getData());
} catch (IOException e) {
e.printStackTrace();
}
}
imgvcomp.setImageBitmap(bitmap);
String img=getStringImage(bitmap);
Log.v(TAG,"base64"+img);//checking in log base64 string to image cropeed image found
}
public String getStringImage(Bitmap bmp){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 90, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}
private void showToastMessage(String message) {
Log.v(TAG, String.format("showToastMessage :: message = %s", message));
// Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
}
why i found the cropped image after selecting from galary?there is no error in error log here is the logcat
E/DynamiteModule: Failed to load module descriptor class: Didn't find class "com.google.android.gms.dynamite.descriptors.com.google.firebase.auth.ModuleDescriptor" on path: DexPathList[[zip file "/data/app/
W/FlurryAgent: Flurry session paused for
1 and remote module com.google.android.gms.tagmanager:8
Selected remote version of com.google.android.gms.tagmanager, version >= 8
No container asset found in /assets/containers. Checking top level /assets directory for container assets.
Tag Manager's event handler WILL NOT be installed (no container loaded)
Tag Manager initilization took 274ms
Using measurement service
Connecting to remote service
Connected to remote service
Processing queued up service tasks: 1
Suspending all threads took: 25.809ms
V/help: /9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAMCAgMCAgMDAwMEAwMEBQgFBQQEBQoHBwYIDAoMDAsK
CwsNDhIQDQ4RDgsLEBYQERMUFRUVDA8XGBYUGBIUFRT/2wBDAQMEBAUEBQkFBQkUDQsNFBQUFBQU
FBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBT/wAARCAzABywDASIA
AhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQA
AAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2Jygg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1BPB/xqWRXKNuXK8cdzWHLrobRtEjhHyoHIV1Odw5B/8A1U2VpJI9y4KE9Scfj709JUUc
qE3c7fSmy7ZI2LP+742oB90+3fn3rFxfM77aGyd1oVfUAhj7cCpbYSNEysQrHjaOlQyKA4K5XA65
71NCrLHuZg4PTAwa0aTVirkDWmVZWwyk4YDgH0qSG1YMwABXgjB5pFkjZ2bac9xg4/z704XRi3Lg
IHGBnr/k09e5LaW4pzIiZGfLGBzyoJpl45KZTBxwPQU2FzudASQuC2Rz7Zp5k3KQRhuoI5x+Hf61
SbWotCrAgU9CWYjdj09frUj7SxC8gc5PAxTgSyZiwc8ZHYd+aTeEZ14IYck9DU66u5peysRhQ4Ib
DEEEsOBSM6BgYyCoHDDpT/3bxN8uQOoPQ/UVHDEuWAOGPTA6UyGk9GPExAJRNzEjO
You can use following code:
public static String encodeTobase64(Bitmap image) {
Bitmap immagex=image;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
immagex.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] b = baos.toByteArray();
String imageEncoded = Base64.encodeToString(b,Base64.DEFAULT);
Log.e("LOOK", imageEncoded);
return imageEncoded;
}
Use below code in onActivityResult()
InputStream imageStream = null;
try {
imageStream = this.getContentResolver().openInputStream(selectedImage);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Bitmap yourSelectedImage = BitmapFactory.decodeStream(imageStream);
encodeTobase64(yourSelectedImage);
Try this...
public String getStringImage(Bitmap bmp){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}
Here is a similar code. I have implemented the same thing in my app. You can select images from either gallery or camera and You can convert it as a base 64. Try this Its working for me. Hope it work for you too
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Base64;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import in.invis.organickerala.utilities.CropOption;
import in.invis.organickerala.R;
public class Profile_Activity extends AppCompatActivity {
private static final int PICK_FROM_CAMERA = 1;
private static final int CROP_FROM_CAMERA = 2;
private static final int PICK_FROM_FILE = 3;
final String[] items = new String[]{"Take From Camera", "Select From Gallery"};
ImageView picture;
AlertDialog.Builder builder;
ArrayAdapter<String> adapter;
private AccountManager mAccountManager;
private int PICK_IMAGE_REQUEST = 1;
private SharedPreferences mPreferences, myPrefs;
private SharedPreferences.Editor myPrefsEdit;
private Uri mImageCaptureUri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
adapter = new ArrayAdapter<String>(this, android.R.layout.select_dialog_item, items);
builder = new AlertDialog.Builder(this);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
// Show the Up button in the action bar.
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setTitle("Profile");
}
// Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
// setSupportActionBar(toolbar);
// getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mPreferences = getSharedPreferences("CurrentUser", MODE_PRIVATE);
myPrefs = getSharedPreferences("URI", MODE_PRIVATE);
myPrefsEdit = myPrefs.edit();
picture = (ImageView) findViewById(R.id.picture);
picture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
builder.setTitle("Select Image");
builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) { //pick from camera
if (item == 0) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
mImageCaptureUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(),
"tmp_avatar_" + String.valueOf(System.currentTimeMillis()) + ".jpg"));
intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
try {
intent.putExtra("return-data", true);
startActivityForResult(intent, PICK_FROM_CAMERA);
} catch (ActivityNotFoundException e) {
e.printStackTrace();
}
} else { //pick from file
Intent intent = new Intent();
intent.setType("Image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Complete action using"), PICK_FROM_FILE);
}
}
});
final AlertDialog dialog = builder.create();
picture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.show();
}
});
//END CAMERA STUFF
}// End OnCreate
});
String temp = myPrefs.getString("url", "defaultString");
try {
byte[] encodeByte = Base64.decode(temp, Base64.DEFAULT);
Bitmap bitmap = BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
picture.setImageBitmap(bitmap);
} catch (Exception e) {
e.getMessage();
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case PICK_FROM_CAMERA:
doCrop();
break;
case PICK_FROM_FILE:
mImageCaptureUri = data.getData();
doCrop();
break;
case CROP_FROM_CAMERA:
Bundle extras = data.getExtras();
if (extras != null) {
Bitmap photo = extras.getParcelable("data");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] b = baos.toByteArray();
String temp = Base64.encodeToString(b, Base64.DEFAULT);
myPrefsEdit.putString("url", temp);
myPrefsEdit.commit();
picture.setImageBitmap(photo);
}
File f = new File(mImageCaptureUri.getPath());
if (f.exists()) f.delete();
break;
}
}
private void doCrop() {
final ArrayList<CropOption> cropOptions = new ArrayList<CropOption>();
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setType("Image/*");
List<ResolveInfo> list = getPackageManager().queryIntentActivities(intent, 0);
int size = list.size();
if (size == 0) {
Toast.makeText(this, "Can not find Image crop app", Toast.LENGTH_SHORT).show();
return;
} else {
intent.setData(mImageCaptureUri);
intent.putExtra("outputX", 300);
intent.putExtra("outputY", 300);
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("scale", true);
intent.putExtra("return-data", true);
if (size != 0) {
Intent i = new Intent(intent);
ResolveInfo res = list.get(0);
i.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
startActivityForResult(i, CROP_FROM_CAMERA);
}
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// handle arrow click here
if (item.getItemId() == android.R.id.home) {
Intent intent = new Intent(Profile_Activity.this,MainActivity.class);
startActivity(intent);
}
return super.onOptionsItemSelected(item);
}
}
This is how I do it on my onActivityResult of my gallery intent.
String imagePath = ImageUtil.getRealPathFromURI(getActivity(), data.getData());
Then converting the whole thing to bitmap.
Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
Here is my getRealPathFromURI method from ImageUtil Class.
public static String getRealPathFromURI(Context context, Uri contentURI) {
String result = null;
String[] projection = {MediaStore.Images.Media.DATA};
try {
Cursor cursor = context.getContentResolver().query(contentURI, projection, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(projection[0]);
result = cursor.getString(columnIndex);
cursor.close();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
And here is my conversion from bitmap to base64.
public static String getBase64(Bitmap bitmap) {
if (bitmap != null) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
return Base64.encodeToString(baos.toByteArray(), Base64.DEFAULT);
}
return null;
}

Capture Image From Camera and Select Image From Gallery of Android Phone Using Android Studio

package com.sourcey.materiallogindemo;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
public class Profile extends AppCompatActivity {
ImageView viewImage;
Button b;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
b=(Button)findViewById(R.id.btnSelectPhoto);
viewImage=(ImageView)findViewById(R.id.viewImage);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
}
});
}
private void selectImage() {
final CharSequence[] options = { "Take Photo", "Choose from Gallery","Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(Profile.this);
builder.setTitle("Add Photo!");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
//boolean result=Utility.checkPermission(Profile.this);
if (options[item].equals("Take Photo"))
{
// startActivityForResult(intent, REQUEST_CAMERA);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");
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);
viewImage.setImageBitmap(bitmap);
String path = android.os.Environment
.getExternalStorageDirectory()
+ File.separator
+ "Phoenix" + 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);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePath[0]);
String picturePath = c.getString(columnIndex);
c.close();
Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
Log.w("path of image from gallery......******************.........", picturePath+"");
viewImage.setImageBitmap(thumbnail);
}
}
}
}
I am new to android.In my app ,i need to set picture from camera or gallery so i used this code(mentioned). gallery option is working fine but when i choose camera ,the app is unfortunately stopped,please help to fix it and i also save the picture in gallery which was taken in camera.
If you are having problem with the image from camera then you can use the following function.
public void fromCamera(){
String path= Environment.getExternalStorageDirectory().getPath() + "/DCIM/Camera/";
File file = new File(path,"IMG_"+System.currentTimeMillis()+".jpg");
file.getParentFile().mkdirs();
try {
file.createNewFile();
}catch (IOException e) {
e.printStackTrace();
}
mPicCaptureUri = Uri.fromFile(file);
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, mPicCaptureUri);
startActivityForResult(intent, REQUEST_CAMERA);
}
And on your OnActivityResult you can get your image and do what you need to do:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK){
if(requestCode == REQUEST_CAMERA){
if(mPicCaptureUri!=null){
//do try to set image here ....
}
}
}
}
And yes do define at the top mPicCaptureUri as:
private Uri mPicCaptureUri = null;
It worked for me .. hope it helps..

Parse.com & Android: How do I save Images to my parse database so that i can use them as a profile picture

I am new at android as well as parse.com. I need a way in which a user can click a button to take a photo or another button to choose a photo from the gallery. Then store the image in my parse.com database so that I can manipulate it with other events in the system. So far I am able to have the user update his status and save to my parse database but I do not know how to manipulate images and ImageViews. Here is my code so far:
public class UpdateActivity extends Activity {
protected EditText mUpdateStatus;
protected Button mUpdateStatusButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update);
//initialization of variables
mUpdateStatus=(EditText)findViewById(R.id.updateStatusUpdate);
mUpdateStatusButton=(Button)findViewById(R.id.updateButtonUpdate);
//code update button click event
mUpdateStatusButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Get current user
ParseUser currentUser=ParseUser.getCurrentUser();//Identifies current user
String currentUserUsername=currentUser.getUsername();//stores username in variable
//Create new variable to store strings
String newStatus=mUpdateStatus.getText().toString();
//Event for an empty status
if (newStatus.isEmpty())
{AlertDialog.Builder builder=new AlertDialog.Builder(UpdateActivity.this);
builder.setMessage("STATUS SHOULD NOT BE EMPTY.");
builder.setTitle("OOPS!");
builder.setPositiveButton("OK",new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog dialog=builder.create();
dialog.show();}
else{
//Save the status in Parse.com
ParseObject statusObject = new ParseObject("Status");//Create a new parse class
statusObject.put("newStatus",newStatus);//Creates a new attribute and adds value from newStatus
statusObject.put("User",currentUserUsername);//Stores username in new parse class
//Save data and initiate callback method
statusObject.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
if(e==null)
{//Event for a Successful storage
Toast.makeText(UpdateActivity.this,getString(R.string.succssfulUpdate),Toast.LENGTH_LONG).show();
//Take user back to profile
Intent main = new Intent(UpdateActivity.this, ProfileActivity.class);
UpdateActivity.this.startActivity(main);
}
else
{//Event for an Unsuccessful storage
AlertDialog.Builder builder=new AlertDialog.Builder(UpdateActivity.this);
builder.setMessage(e.getMessage());
builder.setTitle("SORRY!");
builder.setPositiveButton("OK",new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog dialog=builder.create();
dialog.show();
}
}
});}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_update, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
switch(id) {
case R.id.logoutUpdateMenu:
{//logout the user
ParseUser.logOut();
//Take user back to login
Intent intent = new Intent(UpdateActivity.this, LoginActivity.class);
UpdateActivity.this.startActivity(intent);
UpdateActivity.this.finish();
Toast.makeText(getApplicationContext(), getString(R.string.logout_text), Toast.LENGTH_LONG).show();
break;}
}
return super.onOptionsItemSelected(item);
}
}
A complete example image upload for Parse.com with option to take a photo gallery or the camera.
Activity.class
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.parse.ParseException;
import com.parse.ParseFile;
import com.parse.ParseObject;
import com.parse.SaveCallback;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MainActivity extends ActionBarActivity {
private static int RESULT_LOAD_CAMERA_IMAGE = 2;
private static int RESULT_LOAD_GALLERY_IMAGE = 1;
private String mCurrentPhotoPath;
private ImageView imgPhoto;
private Button btnUploadImage;
private File cameraImageFile;
private TextView mTextView;
#Override
public void onActivityResult (int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == RESULT_LOAD_GALLERY_IMAGE && 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]);
mCurrentPhotoPath = cursor.getString(columnIndex);
cursor.close();
} else if (requestCode == RESULT_LOAD_CAMERA_IMAGE) {
mCurrentPhotoPath = cameraImageFile.getAbsolutePath();
}
File image = new File(mCurrentPhotoPath);
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
Bitmap bitmap = BitmapFactory.decodeFile(image.getAbsolutePath(), bmOptions);
imgPhoto.setImageBitmap(bitmap);
}
}
private File createImageFile () throws IOException {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File folder = new File(storageDir.getAbsolutePath() + "/PlayIOFolder");
if (!folder.exists()) {
folder.mkdir();
}
cameraImageFile = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
folder /* directory */
);
return cameraImageFile;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imgPhoto = (ImageView)findViewById(R.id.imgPhoto);
imgPhoto.setOnClickListener(chooseImageListener);
btnUploadImage = (Button)findViewById(R.id.btnUpload);
btnUploadImage.setOnClickListener(uploadListener);
}
View.OnClickListener chooseImageListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
dialogChooseFrom();
}
};
View.OnClickListener uploadListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
byte[] image = null;
try {
image = readInFile(mCurrentPhotoPath);
}
catch(Exception e) {
e.printStackTrace();
}
// Create the ParseFile
ParseFile file = new ParseFile("picturePath", image);
// Upload the image into Parse Cloud
file.saveInBackground();
// Create a New Class called "ImageUpload" in Parse
ParseObject imgupload = new ParseObject("Image");
// Create a column named "ImageName" and set the string
imgupload.put("Image", "picturePath");
// Create a column named "ImageFile" and insert the image
imgupload.put("ImageFile", file);
// Create the class and the columns
imgupload.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
Toast.makeText(getBaseContext(), "Done!", Toast.LENGTH_LONG).show();
}
});
}
};
private void dialogChooseFrom(){
final CharSequence[] items={"From Gallery","From Camera"};
AlertDialog.Builder chooseDialog =new AlertDialog.Builder(this);
chooseDialog.setTitle("Pick your choice").setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if(items[which].equals("From Gallery")){
Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, RESULT_LOAD_GALLERY_IMAGE);
} else {
try {
File photoFile = createImageFile();
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(photoFile));
startActivityForResult(cameraIntent, RESULT_LOAD_CAMERA_IMAGE);
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
chooseDialog.show();
}
private 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();
}
}
Layout
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity">
<RelativeLayout
android:layout_marginTop="20dp"
android:layout_centerHorizontal="true"
android:layout_width="200dp"
android:layout_height="200dp"
android:background="#ccc">
<ImageView
android:id="#+id/imgPhoto"
android:layout_width="200dp"
android:layout_height="200dp"
/>
<TextView
android:text="Choose a image"
android:layout_centerHorizontal="true"
android:layout_alignParentBottom="true"
android:layout_margin="2dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
<Button
android:id="#+id/btnUpload"
android:text="Upload Photo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"/>
</RelativeLayout>
Android Manifest
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.FLASHLIGHT" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
I have no experience with parse.com but If you are able to put images(bit map) into ParseObject, you just need to call take photo or pick photo action using intent and startActivityForResult. Example:
public void onClickTakePhoto(View view) {
dispatchTakePictureIntent();
}
public void onClickPickPhoto(View view) {
Intent i = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, REQUEST_SELECT_IMAGE);
}
//Code from Android documentation
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if ((requestCode == REQUEST_IMAGE_CAPTURE || requestCode == REQUEST_SELECT_IMAGE) && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
ParseObject statusObject = new ParseObject("Status");
//I think parse has similar support If not this
statusObject.put("profile_photo",imageBitmap);
statusObject.saveInBackground( new Callback(){...});
}
}
You need to convert your Bitmap or any Object into byte[].
And then use following code.
byte[] image= your byte array
final ParseFile files = new ParseFile(image);
files.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException exception) {
if (exception == null) {
ParseUser.getCurrentUser().put("<parse-column-name>", files);
ParseUser.getCurrentUser().saveInBackground();
}
}
});
Hope this helps.
This is how you can upload a file to a Parse server (Back4App):
ByteArrayOutputStream bos = new ByteArrayOutputStream();
newProfileImageBitmap.compress(Bitmap.CompressFormat.PNG, 0, bos);
byte[] bitmapData = bos.toByteArray();
ParseFile newImageFile = new ParseFile(bitmapData);
currentUser.put("userPicture", newImageFile);
currentUser.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
if(e == null) {
// Image has been uploaded
} else {
// An error has happened when upoading
}
}
});

Calling camera from an activity, capturing an image and uploading to a server

In my app, I have a button1 which calls camera, and after capturing the image, it must be saved to the device gallery. When I click on button2, it must open the gallery, and ask to select a picture. When selected, it must be shown on the imageView below these buttons.
Here is my code:
package com.android.imageuploading;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class ImageUploadingActivity extends Activity {
private static final int REQUEST_CODE = 1;
private Bitmap bitmap;
private ImageView imageView;
private Button button_1;
public int TAKE_PICTURE = 1;
private Button button_2;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
imageView = (ImageView) findViewById(R.id.image);
button_1 = (Button) findViewById(R.id.button1);
button_1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
startActivityForResult(intent, TAKE_PICTURE);
}
});
button_2 = (Button) findViewById(R.id.button2);
button_2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
pickImage(getCurrentFocus());
}
});
}
public void pickImage(View view) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(intent, REQUEST_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK)
try {
// We need to recyle unused bitmaps
if (bitmap != null) {
bitmap.recycle();
}
InputStream stream = getContentResolver().openInputStream(
data.getData());
bitmap = BitmapFactory.decodeStream(stream);
stream.close();
imageView.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
super.onActivityResult(requestCode, resultCode, data);
}
public static boolean isIntentAvailable(Context context, String action) {
final PackageManager packageManager = context.getPackageManager();
final Intent intent = new Intent(action);
List<ResolveInfo> list = packageManager.queryIntentActivities(intent,
PackageManager.MATCH_DEFAULT_ONLY);
return list.size() > 0;
}
}
The problem is, when I capture the image, it asks for save or discard. When I click on save, my app crashes, saying:
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { act=inline-data (has extras) }} to activity {com.android.imageuploading/com.android.imageuploading.ImageUploadingActivity}: java.lang.NullPointerException
Where do I need to change the code?
in my case i use this: when i click on save button pic is save and return me path in filePath variable.
String filePath =
Environment.getExternalStorageDirectory() +"/your_image_name.jpeg";
File file = new File(filePath);
Uri output = Uri.fromFile(file);
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, output);
and in onactivityresul() i use this "filePath" .
Capture Image:
public class Camera extends Activity
{
private static final int CAMERA_REQUEST = 1888;
private String selectedImagePath;
WebView webview;
String fileName = "capturedImage.jpg";
private static Uri mCapturedImageURI;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Intent cameraIntent = new Intent(ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (resultCode == RESULT_OK) {
if (requestCode == CAMERA_REQUEST)
{
Bitmap photo = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.JPEG, 40, bytes);
Random randomGenerator = new Random();randomGenerator.nextInt();
String newimagename=randomGenerator.toString()+".jpg";
File f = new File(Environment.getExternalStorageDirectory()
+ File.separator + newimagename);
try {
f.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//write the bytes in file
try {
fo = new FileOutputStream(f.getAbsoluteFile());
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fo.write(bytes.toByteArray());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
uri=f.getAbsolutePath();
//this is the url that where you are saved the image
}
}
Choose Image:
public class ChoosePicture extends Activity
{
private static final int SELECT_PICTURE = 1;
private String selectedImagePath;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
webview=(WebView)findViewById(R.id.webView1);
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(intent, SELECT_PICTURE);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE)
{
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
try {
FileInputStream fileis=new FileInputStream(selectedImagePath);
BufferedInputStream bufferedstream=new BufferedInputStream(fileis);
byte[] bMapArray= new byte[bufferedstream.available()];
bufferedstream.read(bMapArray);
Bitmap bMap = BitmapFactory.decodeByteArray(bMapArray, 0, bMapArray.length);
//this is the image that you are choosen
if (fileis != null)
{
fileis.close();
}
if (bufferedstream != null)
{
bufferedstream.close();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
}

Categories

Resources