I'm working on an android app that produces effects in images. I want the users of my app to have two options.
1) They can choose pictures from Gallery
2) They can capture a new photo from camera
Here is how I'm accomplishing the aforementioned two tasks:
Button takePhotoFromCameraButton;
Button chooseFromGalleryButton;
String imagePath = Environment.getExternalStorageDirectory().getAbsolutePath() + System.currentTimeMillis() + "_image.jpg";
File imageFile = new File(imagePath);
imageUri = Uri.fromFile(imageFile);
In both buttons, I'm passing the same onClickListner.
#Override
public void onClick(View clickedView) {
int clickedViewId = clickedView.getId();
switch(clickedViewId) {
case R.id.takeFromCamera:
Intent imageCaptureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
imageCaptureIntent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(imageCaptureIntent,0);
break;
case R.id.chooseFromGallery:
Intent choosePictureIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(choosePictureIntent, 1);
break;
default:
// As we have only two buttons, and nothing else can be clicked except the buttons. So no need to put
// code in the "DEFAULT CASE"
}
}
And I'm capturing the result from both, the following way:
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
switch(requestCode) {
case 0:
Intent cameraIntent = new Intent(MainOptionsActivity.this,ApplyEffectsActivity.class);
cameraIntent.putExtra("imageFileUri", imageUri);
startActivity(cameraIntent);
break;
case 1:
Uri imageUriForGallery = intent.getData();
Intent galleryIntent = new Intent(MainOptionsActivity.this,ApplyEffectsActivity.class);
galleryIntent.putExtra("imageFileUri", imageUriForGallery);
startActivity(galleryIntent);
break;
}
}
}
The button for gallery images works fine. But when I invoke camera by pressing the second button and capture the image, nothing happens. It stays there till I cancel the camera and come back to my app. I don't receive any image back!
Where I'm wrong? Don't mind this silly question, I'm just a beginner in android! :(
When I implemented mine, I made it work this way through a fragment:
public class ConcertFragment extends Fragment implements SurfaceHolder.Callback {
ImageView toto;
ToggleButton btnFlashlight;
RayMenu menu;
View rootView;
private Camera cam;
boolean hasCamera;
Parameters params;
private int REQUEST_IMAGE_CAPTURE;
Bitmap photo;
Uri imageUri;
public ConcertFragment() {
}
public void startCameraIntent() {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, REQUEST_IMAGE_CAPTURE);
}
#Override
public void onStart() {
super.onStart();
SurfaceView preview = (SurfaceView)getView().findViewById(R.id.background);
SurfaceHolder mHolder = preview.getHolder();
mHolder.addCallback(this);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.concert, menu);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getCamera();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_concert, container, false);
toto = (ImageView) rootView.findViewById(R.id.toto);
return rootView;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if(resultCode != 0)
{
if (requestCode == REQUEST_IMAGE_CAPTURE) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
toto.setImageBitmap(photo);
View content = rootView.findViewById(R.id.toto);
content.setDrawingCacheEnabled(true);
Bitmap bitmap = content.getDrawingCache();
File root = Environment.getExternalStorageDirectory();
File cachePath = new File(root.getAbsolutePath() + "/DCIM/Camera/image.jpg");
try {
cachePath.createNewFile();
FileOutputStream ostream = new FileOutputStream(cachePath);
bitmap.compress(CompressFormat.JPEG, 100, ostream);
ostream.close();
} catch (Exception e) {
e.printStackTrace();
}
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/*");
share.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(cachePath));
startActivity(Intent.createChooser(share,"Share via"));
}
else {
cam.release();
}
}
}
// Get the camera
private void getCamera() {
if (cam != null) {
try {
cam = Camera.open();
params = cam.getParameters();
cam.startPreview();
hasCamera = true;
} catch (RuntimeException e) {
Log.e("Camera Error. Failed to Open. Error: ", e.getMessage());
cam.release();
}
}
}
Hope this helps :) Just ask if you need more information.
How to do it with an activity, instead of fragment
public class MyCameraActivity extends Activity {
private static final int CAMERA_REQUEST = 1888;
private ImageView imageView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.imageView = (ImageView)this.findViewById(R.id.imageView1);
Button photoButton = (Button) this.findViewById(R.id.button1);
photoButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
}
}
}
Related
I Have code which is defined for image (drawable )
Means Image is are already defined but I want user to select Image from Gallery .
SO first I want to get all Images from gallery and then it is show in view and from their user can select Image .
So it means all Images must be saved in array like below .
Any Help for this.
public class StickerSelectActivity extends AppCompatActivity {
public static final String EXTRA_STICKER_ID = "extra_sticker_id";
private final int[] stickerIds = {
R.drawable.abra,
R.drawable.bellsprout,
R.drawable.bracelet,
R.drawable.bullbasaur,
R.drawable.camera,
R.drawable.candy,
R.drawable.caterpie,
R.drawable.charmander,
R.drawable.mankey,
R.drawable.map,
R.drawable.mega_ball,
R.drawable.meowth,
R.drawable.pawprints,
R.drawable.pidgey,
R.drawable.pikachu,
R.drawable.pikachu_1,
R.drawable.pikachu_2,
R.drawable.player,
R.drawable.pointer,
R.drawable.pokebag,
R.drawable.pokeball,
R.drawable.pokeballs,
R.drawable.pokecoin,
R.drawable.pokedex,
R.drawable.potion,
R.drawable.psyduck,
R.drawable.rattata,
R.drawable.revive,
R.drawable.squirtle,
R.drawable.star,
R.drawable.star_1,
R.drawable.superball,
R.drawable.tornado,
R.drawable.venonat,
R.drawable.weedle,
R.drawable.zubat
};
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.select_sticker_activity);
//noinspection ConstantConditions
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.stickers_recycler_view);
GridLayoutManager glm = new GridLayoutManager(this, 3);
recyclerView.setLayoutManager(glm);
List<Integer> stickers = new ArrayList<>(stickerIds.length);
for (Integer id : stickerIds) {
stickers.add(id);
}
recyclerView.setAdapter(new StickersAdapter(stickers, this));
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
private void onStickerSelected(int stickerId) {
Intent intent = new Intent();
intent.putExtra(EXTRA_STICKER_ID, stickerId);
setResult(RESULT_OK, intent);
finish();
}
class StickersAdapter extends RecyclerView.Adapter<StickersAdapter.StickerViewHolder> {
private final List<Integer> stickerIds;
private final Context context;
private final LayoutInflater layoutInflater;
StickersAdapter(#NonNull List<Integer> stickerIds, #NonNull Context context) {
this.stickerIds = stickerIds;
this.context = context;
this.layoutInflater = LayoutInflater.from(context);
}
#Override
public StickerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new StickerViewHolder(layoutInflater.inflate(R.layout.sticker_item, parent, false));
}
#Override
public void onBindViewHolder(StickerViewHolder holder, int position) {
holder.image.setImageDrawable(ContextCompat.getDrawable(context, getItem(position)));
}
#Override
public int getItemCount() {
return stickerIds.size();
}
private int getItem(int position) {
return stickerIds.get(position);
}
class StickerViewHolder extends RecyclerView.ViewHolder {
ImageView image;
StickerViewHolder(View itemView) {
super(itemView);
image = (ImageView) itemView.findViewById(R.id.sticker_image);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int pos = getAdapterPosition();
if (pos >= 0) { // might be NO_POSITION
onStickerSelected(getItem(pos));
}
}
});
}
}
}
}
Its not required If you want to show all available images in gallery in your application. You can use
private Cursor cc = null;
cc = this.getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, null, null, null,
null)
This will give you a connection with files available in gallery. More detailed answer is here
How to implement Image Gallery in Gridview in android?
If In case in your application you have an image view and you want your user to click on the image and then Android should ask if they want to select an image from gallery/camera you can follow this, You can call selectImage method on setOnClickListener on ImageView.
private void selectImage() {
final CharSequence[] items = { "Take Photo", "Choose from Library" };
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Update Profile Photograph");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
boolean result = Utility.checkPermission(getActivity());
if (items[item].equals("Take Photo")) {
if(result)
cameraIntent();
} else if (items[item].equals("Choose from Library")) {
if(result)
galleryIntent();
}
}
});
builder.show();
}
private void cameraIntent() {
Intent takePicture = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
File out = Environment.getExternalStorageDirectory();
out = new File(out, familyMemberId + ".png");
Uri photoURI = FileProvider.getUriForFile(getContext(), getContext().getPackageName() + ".app.provider", out);
takePicture.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePicture, 0);
}
private void galleryIntent() {
Intent pickPhoto = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(pickPhoto , 1);//one can be replaced with any action code
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch(requestCode) {
case 0:
if(resultCode == Activity.RESULT_OK){
File out = Environment.getExternalStorageDirectory();
out = new File(out, familyMemberId + ".png");
Uri photoURI = FileProvider.getUriForFile(getContext(), getContext().getPackageName() + ".app.provider", out);
Toast.makeText(getContext(), photoURI.toString(), Toast.LENGTH_LONG).show();
imageUri = photoURI.toString();
Glide.with(this).load(imageUri).into(familyMemberProfilePick);
}
break;
case 1:
if(resultCode == Activity.RESULT_OK){
Uri selectedImage = imageReturnedIntent.getData();
imageUri = selectedImage.toString();
Glide.with(this).load(imageUri).into(familyMemberProfilePick);
}
break;
}
}
Please don't forget add these in
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<application ...
<provider
android:name=".utility.GenericFileProvider"
android:authorities="${applicationId}.app.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/provider_paths"/>
</provider>
....
</application>
I am developing an app which takes a picture with the camera and allows the user to share it. But the share intent isn't working. I have checked but none are working on my device. I am running the app on an Android 6.0 marshmallow tablet.
Here is my code
public class SharePic extends Activity {
static final int REQUEST_IMAGE_CAPTURE = 1;
ImageView picView;
Button shareBtn;
Bitmap imageBitmap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_share_pic);
picView = (ImageView) findViewById(R.id.picView);
shareBtn = (Button) findViewById(R.id.shareBtn);
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 && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
imageBitmap = (Bitmap) extras.get("data");
picView.setImageBitmap(imageBitmap);
}
}
public void share(View view){
String bitmapPath = MediaStore.Images.Media.insertImage(getContentResolver(), imageBitmap,"title", null);
Uri bitmapUri = Uri.parse(bitmapPath);
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("image/png");
intent.putExtra(Intent.EXTRA_STREAM, bitmapUri);
startActivity(Intent.createChooser(intent , "Share"));
}
}
Any help?
So, when is the share button being called.
I guess you might have to set event listener setOnClickListener on share button click in case you haven't set it in the XML
shareBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
share(v);
}
});
I have an ImageButton which plays the video I recorded. Everything works fine but the thing is I want to play the recorded video(resultvideo) on another activity. I'm new to Android Dev. could someone teach me how to do that, thanks!
Here's my code:
public class MainActivity extends AppCompatActivity {
ImageButton imageButton;
static final int REQUEST_VIDEO_CAPTURE = 1;
VideoView resultvideo;
MediaController mediacontroller;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
resultvideo = (VideoView)findViewById(R.id.videoView);
mediacontroller = new MediaController(MainActivity.this);
mediacontroller.setAnchorView(resultvideo);
resultvideo.setMediaController(mediacontroller);
Button click = (Button)findViewById(R.id.buttonRecord);
resultvideo = (VideoView)findViewById(R.id.videoView);
}
public void dispatchTakeVideoIntent(View v) {
Intent takeVideoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
if (takeVideoIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takeVideoIntent, REQUEST_VIDEO_CAPTURE);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_VIDEO_CAPTURE && resultCode == RESULT_OK) {
Uri videoUri = data.getData();
resultvideo.setVideoURI(videoUri);
resultvideo.pause();
}
imageButton = (ImageButton) findViewById(R.id.imageButton);
{
imageButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, Main2Activity.class));
resultvideo.start();
}
});
}
}
}
You can send Uri of video via Intent to another activity
Intent intent = new Intent(MainActivity.this, Main2Activity.class);
intent.putExtra("VIDEO_URI", videoUri.toString());
startActivity(intent);
And then in Main2Activity in onCreate method get videoUri like this:
String uri = getIntent().getStringExtra("VIDEO_URI");
Uri videoUri = Uri.parse(uri);
In my app, I have Written code for getting the Image from gallery and cropped and set into the Image View but the image is not set. If i didnt use crop option coding means its working fine.
I dont know how to use crop option in Fragment.
Here my code:
ProfileFragment:
public class ProfileFragment extends Fragment {
private ImageView imageView;
private static final int SELECT_PHOTO = 1;
private Uri mSelectedImageUri = null;
Button browseProfilePic;
#Override
public View onCreateView(final LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
setHasOptionsMenu(true);//For option menu
View view = inflater.inflate(R.layout.fragment_layout_profilepic, container,
false);
imageView = (ImageView)view.findViewById(R.id.profile_image);
browseProfilePic = (Button) view.findViewById(R.id.btn_pick);
browseProfilePic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
// Show only images, no videos or anything else
intent.setType("image/*");
//Crop option
intent.putExtra("crop", "true");
intent.putExtra("aspectX",0);
intent.putExtra("aspectY",0);
intent.putExtra("outputX",200);
intent.putExtra("outputY",150);
//intent.setAction(Intent.ACTION_GET_CONTENT);
intent.putExtra("return-data",true);
// Always show the chooser (if there are multiple options available)
startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PHOTO);
}
});
return view;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.d("Request Code:", String.valueOf(requestCode));
Log.d("Result Code:", String.valueOf(resultCode));
Log.d("Data:",String.valueOf(data));
if (requestCode == SELECT_PHOTO && data != null) {
mSelectedImageUri = data.getData();
Log.d("Uri:", String.valueOf(mSelectedImageUri));
//User had pick an image.
Cursor cursor = getActivity().getContentResolver().query(mSelectedImageUri, new String[]{android.provider.MediaStore.Images.ImageColumns.DATA}, null, null, null);
cursor.moveToFirst();
//Link to the image
final String imageFilePath = cursor.getString(0);
cursor.close();
File file = new File(imageFilePath);
Log.d("File:", String.valueOf(file));
if (file != null) {
Bitmap bMap = BitmapFactory.decodeFile(String.valueOf(file));
imageView.setImageBitmap(bMap);
}
}
super.onActivityResult(requestCode, resultCode, data);
}
}
Please anyone help to fix!
Thanks in advance..
Hello please help me have need upload current image in image view
I have need upload the image capture in telephone
`public class MainActivity extends Activity {
Button button;
private static final int CAMERA_REQUEST = 1888;
private ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the view from main.xml
setContentView(R.layout.main);
this.imageView = (ImageView)this.findViewById(R.id.imageView1);
Button photoButton = (Button) this.findViewById(R.id.button1);
photoButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
}
// Locate the button in main.xml
button = (Button) findViewById(R.id.uploadbtn);
// Capture button clicks
button.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// Locate the image in res > drawable-hdpi
Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
R.drawable.androidbegin);
// Convert it to byte
ByteArrayOutputStream stream = new ByteArrayOutputStream();
// Compress image to lower quality scale 1 - 100
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] image = stream.toByteArray();
// Create the ParseFile
ParseFile file = new ParseFile("androidbegin.png", image);
// Upload the image into Parse Cloud
file.saveInBackground();
// Create a New Class called "ImageUpload" in Parse
ParseObject imgupload = new ParseObject("ImageUpload");
// Create a column named "ImageName" and set the string
imgupload.put("ImageName", "AndroidBegin Logo");
// Create a column named "ImageFile" and insert the image
imgupload.put("ImageFile", file);
// Create the class and the columns
imgupload.saveInBackground();
// Show a simple toast message
Toast.makeText(MainActivity.this, "Image Uploaded",
Toast.LENGTH_SHORT).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.main, menu);
return true;
}
}`
Why dont you just do most of the work on the onActivityResult method?
Button take_picture = (Button) findViewById(R.id.addPicButton);
take_picture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dispatchTakePictureIntent();
}
});
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
byte[] image_byte_array;
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.PNG, 100, stream);
image_byte_array = stream.toByteArray();
imageView.setImageBitmap(photo);
ParseFile pf = new ParseFile("Picture", image_byte_array);
pf.saveInBackground();
}
I messed around with parse for a while and made an app, check this repo out... maybe youl find some useful code. https://github.com/Aquaballin/HackingVeggies/tree/master/ProduceList/src/com/parse/starter
good luck bro!