This question already has answers here:
Low picture/image quality when capture from camera
(3 answers)
Closed 5 years ago.
I want to take a picture from the Camera and Upload it to Server, but when I take a Picture from the Camera and Upload the Picture is low Resolution.
Code :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CaptureImageFromCamera = (ImageView)findViewById(R.id.imageView);
CaptureImageFromCamera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, 1);
}
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == 1)
try {
onCaptureImageResult(data);
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void onCaptureImageResult(Intent data) throws IOException {
bitmap = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes;
bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, bytes);
File destination = new File(Environment.getExternalStorageDirectory(),
"DCA/Attachment/" + System.currentTimeMillis() + ".png");
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();
}
ImageViewHolder.setImageBitmap(bitmap);
}
Can be seen that the image quality is low resolution.
Is there a way to solve this problem?
[UPDATE] HOW I TO SOLVE THIS
I read the article here to solve this problem
Note: Read from the start page
package com.example.admin.camsdemo;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity {
Button captureimage;
ContentValues cv;
Uri imageUri;
ImageView imgView;
public static final int PICTURE_RESULT=111;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
captureimage=(Button)findViewById(R.id.opencamera);
imgView=(ImageView)findViewById(R.id.img);
captureimage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
cv = new ContentValues();
cv.put(MediaStore.Images.Media.TITLE, "My Picture");
cv.put(MediaStore.Images.Media.DESCRIPTION, "From Camera");
imageUri = getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, cv);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, PICTURE_RESULT);
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case PICTURE_RESULT:
if (requestCode == PICTURE_RESULT)
if (resultCode == Activity.RESULT_OK) {
try {
Bitmap thumbnail = MediaStore.Images.Media.getBitmap(
getContentResolver(), imageUri);
imgView.setImageBitmap(thumbnail);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
Try using TextureView.SurfaceTextureListener and camera.takePicture(shutterCallback, rawCallback, pictureCallback)
For images taken from camera, you should consider JPEG compression. PNG is more suitable for icons where the colors used are few.
Related
In my project, I am capturing image from the camera. I am taking the full-size image from the app (instead of taking thumbnail). Captured image is of very big size which is 7 to 18 mb. When I have taken image from my default camera app, the size was roughly 2.5 mb only. As well as it's taking lot of time(6-10 seconds) to load and save to the folder. This happening only when I am using the android device, on emulator it's working good. This is my code:
package com.stegano.strenggeheim.fragment;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.stegano.strenggeheim.BuildConfig;
import com.stegano.strenggeheim.R;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.UUID;
public class FragmentEncode extends Fragment {
private static final String MESSAGE_IMAGE_SAVED = "Image Saved!";;
private static final String MESSAGE_FAILED = "Failed!";
private static final String IMAGE_DIRECTORY = "/StrengGeheim";
private static final int GALLERY = 0, CAMERA = 1;
private File capturedImage;
TextView imageTextMessage;
ImageView loadImage;
public FragmentEncode() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
private void galleryIntent() {
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, GALLERY);
}
private void cameraIntent() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
Uri fileUri = getOutputMediaFileUri();
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(intent, CAMERA);
}
private Uri getOutputMediaFileUri() {
try {
capturedImage = getOutputMediaFile();
return FileProvider.getUriForFile(getActivity(), BuildConfig.APPLICATION_ID + ".provider", capturedImage);
}
catch (IOException ex){
ex.printStackTrace();
Toast.makeText(getContext(), MESSAGE_FAILED, Toast.LENGTH_SHORT).show();
}
return null;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_encode, container, false);
imageTextMessage = view.findViewById(R.id.imageTextMessage);
loadImage = view.findViewById(R.id.loadImage);
loadImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showPictureDialog();
}
});
return view;
}
private void showPictureDialog(){
AlertDialog.Builder pictureDialog = new AlertDialog.Builder(getContext());
pictureDialog.setTitle("Select Action");
String[] pictureDialogItems = {
"Select photo from gallery",
"Capture photo from camera",
"Cancel"
};
pictureDialog.setItems(pictureDialogItems,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:
galleryIntent();
break;
case 1:
cameraIntent();
break;
case 2:
dialog.dismiss();
break;
}
}
});
pictureDialog.show();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == getActivity().RESULT_CANCELED) {
return;
}
try {
if (requestCode == GALLERY && data != null) {
Bitmap bitmap = getBitmapFromData(data, getContext());
File mediaFile = getOutputMediaFile();
String path = saveImage(bitmap, mediaFile);
Log.println(Log.INFO, "Message", path);
Toast.makeText(getContext(), MESSAGE_IMAGE_SAVED, Toast.LENGTH_SHORT).show();
loadImage.setImageBitmap(bitmap);
imageTextMessage.setVisibility(View.INVISIBLE);
} else if (requestCode == CAMERA) {
final Bitmap bitmap = BitmapFactory.decodeFile(capturedImage.getAbsolutePath());
loadImage.setImageBitmap(bitmap);
saveImage(bitmap, capturedImage);
Toast.makeText(getContext(), MESSAGE_IMAGE_SAVED, Toast.LENGTH_SHORT).show();
imageTextMessage.setVisibility(View.INVISIBLE);
}
} catch (Exception ex) {
ex.printStackTrace();
Toast.makeText(getContext(), MESSAGE_FAILED, Toast.LENGTH_SHORT).show();
}
}
private Bitmap getBitmapFromData(Intent intent, Context context){
Uri selectedImage = intent.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = context.getContentResolver()
.query(selectedImage,filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
return BitmapFactory.decodeFile(picturePath);
}
private String saveImage(Bitmap bmpImage, File mediaFile) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bmpImage.compress(Bitmap.CompressFormat.PNG, 50, bytes);
try {
FileOutputStream fo = new FileOutputStream(mediaFile);
fo.write(bytes.toByteArray());
MediaScannerConnection.scanFile(getContext(),
new String[]{mediaFile.getPath()},
new String[]{"image/png"}, null);
fo.close();
return mediaFile.getAbsolutePath();
} catch (IOException ex) {
ex.printStackTrace();
}
return "";
}
private File getOutputMediaFile() throws IOException {
File encodeImageDirectory =
new File(Environment.getExternalStorageDirectory() + IMAGE_DIRECTORY);
if (!encodeImageDirectory.exists()) {
encodeImageDirectory.mkdirs();
}
String uniqueId = UUID.randomUUID().toString();
File mediaFile = new File(encodeImageDirectory, uniqueId + ".png");
mediaFile.createNewFile();
return mediaFile;
}
}
Something you could do is download an available API online, or, if need be, dowload the source code of some online compressor. Then you could use it as a model. Never directly use the source code. One that is widely supported across languages is: https://optimus.keycdn.com/support/image-compression-api/
I am taking the image from the camera and getting the File. So, I am saving the image directly in file location which I generated using getOutputMediaFile() method. For that I am overloading saveImage() method like this:
private void saveImage(File mediaImage) {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri contentUri = Uri.fromFile(mediaImage);
mediaScanIntent.setData(contentUri);
getContext().sendBroadcast(mediaScanIntent);
}
This method will put the image in the desired file location and also accessible to the Gallery for other apps. This method is same as galleryAddPic() method on this link Taking Photos Simply
But In the case of picking a photo from the Gallery, I will have to create the File in the desired location and write the bytes of the picked image into that file, so the old saveImage() method will not change.
In onActivityResult method, this is how I used overloaded saveImage() method:
else if (requestCode == CAMERA) {
saveImage(imageFile);
Bitmap bitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath());
loadImage.setImageBitmap(bitmap);
Toast.makeText(getContext(), MESSAGE_IMAGE_SAVED, Toast.LENGTH_SHORT).show();
imageTextMessage.setVisibility(View.INVISIBLE);
}
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..
I am a very young self taught developer and I'm working on my first major project, which requires to start a camera intent once pressed, save the image that the user took and display it in a custom dialog.
I got it to work, but i stored the returned bitmap in onactivityresult so the picture is compressed and that destroys the functionality of the app.
HERE IS THE CODE THAT DOES WORK:
start intent:
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 1);
Recieve Intent and send data to dialog:
Bundle bundle = data.getExtras();
File file = new File(getCacheDir() + "/app"
+ System.currentTimeMillis() + ".jpg");
Bitmap bitmap = (Bitmap) bundle.get("data");
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 100 /* ignored for PNG */,
bos);
byte[] bitmapdata = bos.toByteArray();
// write the bytes in file
FileOutputStream fos;
try {
fos = new FileOutputStream(file);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fos = new FileOutputStream(file);
fos.write(bitmapdata);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mdialog.setPic(file.getAbsolutePath());
Display the picture in the custom dialog:
public void setPic(final String mURi) {
this.mURI = mURi;
if (mURI != null) {
hwPic.postDelayed(new Runnable() {
#Override
public void run() {
Drawable d = Drawable.createFromPath(mURI);
hwPic.setImageDrawable(d);;
hwPic.setVisibility(View.VISIBLE);
}
}, 1000);
}
}
This works fine but since the picture is compressed any reasonably sized font in the picture is blury and illegible.
HERE IS THE CODE THAT DOES NOT WORK:
Initialize Variable:
private String MURID;
Start intent:
File file = new File(getCacheDir() + "/app"
+ System.currentTimeMillis() + ".jpg");
if(!file.exists()){
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{
file.delete();
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
MURID=file.getAbsolutePath();
Intent intent = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT , Uri.parse(MURID));
startActivityForResult(intent, 1);
recieve intent and send to mydialog:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {// camera intent for the dialog picture
if (resultCode == RESULT_OK) {
mdialog.setPic(MURID);
}
}
}
setpic remains the same(in the dialog):
public void setPic(final String mURi) {
this.mURI = mURi;
if (mURI != null) {
hwPic.postDelayed(new Runnable() {
#Override
public void run() {
Drawable d = Drawable.createFromPath(mURI);
hwPic.setImageDrawable(d);;
hwPic.setVisibility(View.VISIBLE);
}
}, 1000);
}
}
Im not getting any response from it and logcat didnt give me any errors either, what seems to be the problem? any help would be greatly apprecieated.
BTW: i want this to work with phones without sdcards as well.
Third-party camera apps cannot write to your getCacheDir(), and some may get confused if you point to an existing file. Use external storage instead:
package com.commonsware.android.camcon;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import java.io.File;
public class CameraContentDemoActivity extends Activity {
private static final int CONTENT_REQUEST=1337;
private File output=null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent i=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File dir=
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
output=new File(dir, "CameraContentDemo.jpeg");
i.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(output));
startActivityForResult(i, CONTENT_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
if (requestCode == CONTENT_REQUEST) {
if (resultCode == RESULT_OK) {
Intent i=new Intent(Intent.ACTION_VIEW);
i.setDataAndType(Uri.fromFile(output), "image/jpeg");
startActivity(i);
finish();
}
}
}
}
(from this sample project in this book)
BTW: i want this to work with phones without sdcards as well.
External storage is not removable storage.
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.
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);
}
}