ボタンをクリックするだけでカメラが開き、クリックして画像をキャプチャできるモジュールを書きたい。画像が気に入らない場合は、削除して別の画像を1つクリックしてからその画像を選択すると元に戻ってその画像がアクティビティに表示されます。
これは、カメラアプリを起動して画像を取得して表示するアクティビティの例です。
package edu.gvsu.cis.masl.camerademo;
import Android.app.Activity;
import Android.content.Intent;
import Android.graphics.Bitmap;
import Android.os.Bundle;
import Android.view.View;
import Android.widget.Button;
import Android.widget.ImageView;
public class MyCameraActivity extends Activity
{
private static final int CAMERA_REQUEST = 1888;
private ImageView imageView;
private static final int MY_CAMERA_PERMISSION_CODE = 100;
@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)
{
if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED)
{
requestPermissions(new String[]{Manifest.permission.CAMERA}, MY_CAMERA_PERMISSION_CODE);
}
else
{
Intent cameraIntent = new Intent(Android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
}
});
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults)
{
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == MY_CAMERA_PERMISSION_CODE)
{
if (grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
Toast.makeText(this, "camera permission granted", Toast.LENGTH_LONG).show();
Intent cameraIntent = new Intent(Android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
else
{
Toast.makeText(this, "camera permission denied", Toast.LENGTH_LONG).show();
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == CAMERA_REQUEST && resultCode == Activity.RESULT_OK)
{
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
}
}
}
}
カメラアプリ自体には、画像を確認/再撮影する機能があり、画像が受け入れられると、アクティビティに表示されます。
上記のアクティビティが使用するレイアウトは次のとおりです。これは単純にid button1のButtonとid imageview1のImageViewを含むLinearLayoutです。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:Android="http://schemas.Android.com/apk/res/Android"
Android:orientation="vertical"
Android:layout_width="fill_parent"
Android:layout_height="fill_parent"
>
<Button Android:id="@+id/button1" Android:layout_width="wrap_content" Android:layout_height="wrap_content" Android:text="@string/photo"></Button>
<ImageView Android:id="@+id/imageView1" Android:layout_height="wrap_content" Android:src="@drawable/icon" Android:layout_width="wrap_content"></ImageView>
</LinearLayout>
最後にもう1つ詳しく、必ず追加してください。
<uses-feature Android:name="Android.hardware.camera"></uses-feature>
カメラがアプリの機能にとってオプションであるかどうか。パーミッションでrequireをfalseに設定してください。このような
<uses-feature Android:name="Android.hardware.camera" Android:required="false"></uses-feature>
あなたのmanifest.xmlに。
これが機能するまでに数時間かかりました。コードは、ほとんど同じですが、 developer.Android.com からコピーしたものです。
AndroidManifest.xml
でこの許可を要求します。
<uses-permission Android:name="Android.permission.WRITE_EXTERNAL_STORAGE" />
あなたのActivity
で、これを定義することから始めましょう:
static final int REQUEST_IMAGE_CAPTURE = 1;
private Bitmap mImageBitmap;
private String mCurrentPhotoPath;
private ImageView mImageView;
それからIntent
でこのonClick
を起動します。
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (cameraIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
Log.i(TAG, "IOException");
}
// Continue only if the File was successfully created
if (photoFile != null) {
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
startActivityForResult(cameraIntent, REQUEST_IMAGE_CAPTURE);
}
}
以下のサポート方法を追加してください。
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, // prefix
".jpg", // suffix
storageDir // directory
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = "file:" + image.getAbsolutePath();
return image;
}
次に結果を受け取ります。
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
try {
mImageBitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), Uri.parse(mCurrentPhotoPath));
mImageView.setImageBitmap(mImageBitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
それがうまくいったのはMediaStore.Images.Media.getBitmap(this.getContentResolver(), Uri.parse(mCurrentPhotoPath))
です。これは developer.Android.com のコードとは異なります。元のコードは私にFileNotFoundException
を与えました。
写真を撮る+ギャラリーから選択:
a = (ImageButton)findViewById(R.id.imageButton1);
a.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
selectImage();
}
});
}
private File savebitmap(Bitmap bmp) {
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
OutputStream outStream = null;
// String temp = null;
File file = new File(extStorageDirectory, "temp.png");
if (file.exists()) {
file.delete();
file = new File(extStorageDirectory, "temp.png");
}
try {
outStream = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.PNG, 100, outStream);
outStream.flush();
outStream.close();
} catch (Exception e) {
e.printStackTrace();
return null;
}
return file;
}
@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;
}
private void selectImage() {
final CharSequence[] options = { "Take Photo", "Choose from Gallery","Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Add Photo!");
builder.setItems(options, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int item) {
if (options[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));
//pic = 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) {
//h=0;
File f = new File(Environment.getExternalStorageDirectory().toString());
for (File temp : f.listFiles()) {
if (temp.getName().equals("temp.jpg")) {
f = temp;
File photo = new File(Environment.getExternalStorageDirectory(), "temp.jpg");
//pic = photo;
break;
}
}
try {
Bitmap bitmap;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),
bitmapOptions);
a.setImageBitmap(bitmap);
String path = Android.os.Environment
.getExternalStorageDirectory()
+ File.separator
+ "Phoenix" + File.separator + "default";
//p = path;
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);
//pic=file;
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();
// h=1;
//imgui = selectedImage;
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+"");
a.setImageBitmap(thumbnail);
}
}
私はそれがかなり古いスレッドであることを知っています、しかしonActivityResultのデータがnullであるので、ユーザーがカメラを回転させるとき、これらの解決策はすべて完成していないし、いくつかのデバイス上で動きません。だからここに私は多くのデバイス上でテストし、今のところ何の問題にも直面していない解決策です。
まずあなたのアクティビティであなたのUri変数を宣言します。
private Uri uriFilePath;
次に、キャプチャした画像を保存するための一時フォルダを作成し、カメラで画像をキャプチャするようにします。
PackageManager packageManager = getActivity().getPackageManager();
if (packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
File mainDirectory = new File(Environment.getExternalStorageDirectory(), "MyFolder/tmp");
if (!mainDirectory.exists())
mainDirectory.mkdirs();
Calendar calendar = Calendar.getInstance();
uriFilePath = Uri.fromFile(new File(mainDirectory, "IMG_" + calendar.getTimeInMillis()));
intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, uriFilePath);
startActivityForResult(intent, 1);
}
そして今ここで最も重要なことの1つが来ます、あなたがそれをしないで、あなたがカメラを使用している間に彼の装置を回転させたならばあなたのuriはnullになるので.
@Override
protected void onSaveInstanceState(Bundle outState) {
if (uriFilePath != null)
outState.putString("uri_file_path", uriFilePath.toString());
super.onSaveInstanceState(outState);
}
その後、あなたのonCreateメソッドであなたのURIを常に回復するべきです:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
if (uriFilePath == null && savedInstanceState.getString("uri_file_path") != null) {
uriFilePath = Uri.parse(savedInstanceState.getString("uri_file_path"));
}
}
}
そしてここにあなたのUriをonActivityResultに入れる最後の部分が来ます:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
String filePath = uriFilePath.getPath(); // Here is path of your captured image, so you can create bitmap from it, etc.
}
}
}
P.S CameraとExtのアクセス許可を追加することを忘れないでください。マニフェストへのストレージの書き込み.
カメラ について読んでおく必要があります。 (私はあなたが望むことをすると思います、あなたは現在の画像をあなたのアプリに保存し、そこで選択/削除をし、そしてカメラの中で直接再試行するよりむしろもう一度試みるためにカメラを思い出す必要があります。)
これは私がカメラ画像をキャプチャして保存するために使ったコードで、それをimageviewに表示します。あなたはあなたの必要性に従って使うことができます。
カメラの画像を特定の場所に保存してからその場所から取得し、それをバイト配列に変換する必要があります。
これはキャプチャカメラの画像アクティビティを開くためのメソッドです。
private static final int CAMERA_PHOTO = 111;
private Uri imageToUploadUri;
private void captureCameraImage() {
Intent chooserIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(Environment.getExternalStorageDirectory(), "POST_IMAGE.jpg");
chooserIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
imageToUploadUri = Uri.fromFile(f);
startActivityForResult(chooserIntent, CAMERA_PHOTO);
}
onActivityResult()メソッドは次のようになります。
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_PHOTO && resultCode == Activity.RESULT_OK) {
if(imageToUploadUri != null){
Uri selectedImage = imageToUploadUri;
getContentResolver().notifyChange(selectedImage, null);
Bitmap reducedSizeBitmap = getBitmap(imageToUploadUri.getPath());
if(reducedSizeBitmap != null){
ImgPhoto.setImageBitmap(reducedSizeBitmap);
Button uploadImageButton = (Button) findViewById(R.id.uploadUserImageButton);
uploadImageButton.setVisibility(View.VISIBLE);
}else{
Toast.makeText(this,"Error while capturing Image",Toast.LENGTH_LONG).show();
}
}else{
Toast.makeText(this,"Error while capturing Image",Toast.LENGTH_LONG).show();
}
}
}
これがonActivityResult()で使用されるgetBitmap()メソッドです。カメラキャプチャ画像のビットマップを取得している間に可能なすべてのパフォーマンスの向上を行いました。
private Bitmap getBitmap(String path) {
Uri uri = Uri.fromFile(new File(path));
InputStream in = null;
try {
final int IMAGE_MAX_SIZE = 1200000; // 1.2MP
in = getContentResolver().openInputStream(uri);
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(in, null, o);
in.close();
int scale = 1;
while ((o.outWidth * o.outHeight) * (1 / Math.pow(scale, 2)) >
IMAGE_MAX_SIZE) {
scale++;
}
Log.d("", "scale = " + scale + ", orig-width: " + o.outWidth + ", orig-height: " + o.outHeight);
Bitmap b = null;
in = getContentResolver().openInputStream(uri);
if (scale > 1) {
scale--;
// scale to max possible inSampleSize that still yields an image
// larger than target
o = new BitmapFactory.Options();
o.inSampleSize = scale;
b = BitmapFactory.decodeStream(in, null, o);
// resize to desired dimensions
int height = b.getHeight();
int width = b.getWidth();
Log.d("", "1th scale operation dimenions - width: " + width + ", height: " + height);
double y = Math.sqrt(IMAGE_MAX_SIZE
/ (((double) width) / height));
double x = (y / height) * width;
Bitmap scaledBitmap = Bitmap.createScaledBitmap(b, (int) x,
(int) y, true);
b.recycle();
b = scaledBitmap;
System.gc();
} else {
b = BitmapFactory.decodeStream(in);
}
in.close();
Log.d("", "bitmap size - width: " + b.getWidth() + ", height: " +
b.getHeight());
return b;
} catch (IOException e) {
Log.e("", e.getMessage(), e);
return null;
}
}
それが役に立てば幸い!
カメラから写真をキャプチャし、ギャラリーから画像を選択して、レイアウトまたはイメージビューの背景に設定します。これがサンプルコードです。
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.graphics.drawable.BitmapDrawable;
import Android.graphics.drawable.Drawable;
import Android.net.Uri;
import Android.os.Bundle;
import Android.os.Environment;
import Android.provider.MediaStore;
import Android.util.Log;
import Android.view.View;
import Android.view.View.OnClickListener;
import Android.widget.AdapterView;
import Android.widget.AdapterView.OnItemClickListener;
import Android.widget.GridView;
import Android.widget.ImageView;
import Android.widget.LinearLayout;
public class Post_activity extends Activity
{
final int TAKE_PICTURE = 1;
final int ACTIVITY_SELECT_IMAGE = 2;
ImageView openCameraOrGalleryBtn,cancelBtn;
LinearLayout backGroundImageLinearLayout;
public void onCreate(Bundle savedBundleInstance) {
super.onCreate(savedBundleInstance);
overridePendingTransition(R.anim.slide_up,0);
setContentView(R.layout.post_activity);
backGroundImageLinearLayout=(LinearLayout)findViewById(R.id.background_image_linear_layout);
cancelBtn=(ImageView)findViewById(R.id.cancel_icon);
openCameraOrGalleryBtn=(ImageView)findViewById(R.id.camera_icon);
openCameraOrGalleryBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
selectImage();
}
});
cancelBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
overridePendingTransition(R.anim.slide_down,0);
finish();
}
});
}
public void selectImage()
{
final CharSequence[] options = { "Take Photo", "Choose from Gallery","Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(Post_activity.this);
builder.setTitle("Add Photo!");
builder.setItems(options,new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
if(options[which].equals("Take Photo"))
{
Intent cameraIntent = new Intent(Android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, TAKE_PICTURE);
}
else if(options[which].equals("Choose from Gallery"))
{
Intent intent=new Intent(Intent.ACTION_PICK,Android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, ACTIVITY_SELECT_IMAGE);
}
else if(options[which].equals("Cancel"))
{
dialog.dismiss();
}
}
});
builder.show();
}
public void onActivityResult(int requestcode,int resultcode,Intent intent)
{
super.onActivityResult(requestcode, resultcode, intent);
if(resultcode==RESULT_OK)
{
if(requestcode==TAKE_PICTURE)
{
Bitmap photo = (Bitmap)intent.getExtras().get("data");
Drawable drawable=new BitmapDrawable(photo);
backGroundImageLinearLayout.setBackgroundDrawable(drawable);
}
else if(requestcode==ACTIVITY_SELECT_IMAGE)
{
Uri selectedImage = intent.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));
Drawable drawable=new BitmapDrawable(thumbnail);
backGroundImageLinearLayout.setBackgroundDrawable(drawable);
}
}
}
public void onBackPressed() {
super.onBackPressed();
//overridePendingTransition(R.anim.slide_down,0);
}
}
Add these permission in Androidmenifest.xml file
<uses-permission Android:name="Android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission Android:name="Android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission Android:name="Android.permission.CAMERA"/>
活動中:
@Override
protected void onCreate(Bundle savedInstanceState) {
image = (ImageView) findViewById(R.id.imageButton);
image.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
try {
SimpleDateFormat sdfPic = new SimpleDateFormat(DATE_FORMAT);
currentDateandTime = sdfPic.format(new Date()).replace(" ", "");
File imagesFolder = new File(IMAGE_PATH, currentDateandTime);
imagesFolder.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = IMAGE_NAME + n + IMAGE_FORMAT;
File file = new File(imagesFolder, fname);
outputFileUri = Uri.fromFile(file);
cameraIntent= new Intent(
Android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(cameraIntent, CAMERA_DATA);
}catch(Exception e) {
e.printStackTrace();
}
}
});
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode) {
case CAMERA_DATA :
final int IMAGE_MAX_SIZE = 300;
try {
// Bitmap bitmap;
File file = null;
FileInputStream fis;
BitmapFactory.Options opts;
int resizeScale;
Bitmap bmp;
file = new File(outputFileUri.getPath());
// This bit determines only the width/height of the
// bitmap
// without loading the contents
opts = new BitmapFactory.Options();
opts.inJustDecodeBounds = true;
fis = new FileInputStream(file);
BitmapFactory.decodeStream(fis, null, opts);
fis.close();
// Find the correct scale value. It should be a power of
// 2
resizeScale = 1;
if (opts.outHeight > IMAGE_MAX_SIZE
|| opts.outWidth > IMAGE_MAX_SIZE) {
resizeScale = (int) Math.pow(2, (int) Math.round(Math.log(IMAGE_MAX_SIZE/ (double) Math.max(opts.outHeight, opts.outWidth)) / Math.log(0.5)));
}
// Load pre-scaled bitmap
opts = new BitmapFactory.Options();
opts.inSampleSize = resizeScale;
fis = new FileInputStream(file);
bmp = BitmapFactory.decodeStream(fis, null, opts);
Bitmap getBitmapSize = BitmapFactory.decodeResource(
getResources(), R.drawable.male);
image.setLayoutParams(new RelativeLayout.LayoutParams(
200,200));//(width,height);
image.setImageBitmap(bmp);
image.setRotation(90);
fis.close();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 70, baos);
imageByte = baos.toByteArray();
break;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
layout.xml内で:
enter code here
<RelativeLayout
Android:id="@+id/relativeLayout2"
Android:layout_width="wrap_content"
Android:layout_height="wrap_content">
<ImageView
Android:id="@+id/imageButton"
Android:layout_width="wrap_content"
Android:layout_height="wrap_content"
Android:src="@drawable/XXXXXXX"
Android:textAppearance="?android:attr/textAppearanceSmall" />
manifest.xml内:
<uses-permission Android:name="Android.permission.CAMERA" /> <uses-feature Android:name="Android.hardware.camera" />
あなたはサムネイル画像でカスタムカメラを使うことができます。あなたは私の project を見ることができます。
ここでは、カメラまたはギャラリーを開き、選択した画像をimageviewに設定できます
private static final String IMAGE_DIRECTORY = "/YourDirectName";
private Context mContext;
private CircleImageView circleImageView; // imageview
private int GALLERY = 1, CAMERA = 2;
マニフェストに権限を追加します
<uses-permission Android:name="Android.permission.CAMERA" />
<uses-permission Android:name="Android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission Android:name="Android.PERMISSION.READ_EXTERNAL_STORAGE" />
onCreate() に
requestMultiplePermissions(); // check permission
circleImageView = findViewById(R.id.profile_image);
circleImageView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
showPictureDialog();
}
});
オプションダイアログボックスを表示する(カメラまたはギャラリーから画像を選択するため)
private void showPictureDialog() {
AlertDialog.Builder pictureDialog = new AlertDialog.Builder(this);
pictureDialog.setTitle("Select Action");
String[] pictureDialogItems = {"Select photo from gallery", "Capture photo from camera"};
pictureDialog.setItems(pictureDialogItems,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:
choosePhotoFromGallary();
break;
case 1:
takePhotoFromCamera();
break;
}
}
});
pictureDialog.show();
}
ギャラリーから写真を取得
public void choosePhotoFromGallary() {
Intent galleryIntent = new Intent(Intent.ACTION_PICK, Android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, GALLERY);
}
カメラから写真を取得する
private void takePhotoFromCamera() {
Intent intent = new Intent(Android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAMERA);
}
画像が選択またはキャプチャされたら、
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == this.RESULT_CANCELED) {
return;
}
if (requestCode == GALLERY) {
if (data != null) {
Uri contentURI = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), contentURI);
String path = saveImage(bitmap);
Toast.makeText(getApplicationContext(), "Image Saved!", Toast.LENGTH_SHORT).show();
circleImageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Failed!", Toast.LENGTH_SHORT).show();
}
}
} else if (requestCode == CAMERA) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
circleImageView.setImageBitmap(thumbnail);
saveImage(thumbnail);
Toast.makeText(getApplicationContext(), "Image Saved!", Toast.LENGTH_SHORT).show();
}
}
今、絵を保存する時が来ました
public String saveImage(Bitmap myBitmap) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
myBitmap.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
File wallpaperDirectory = new File(Environment.getExternalStorageDirectory() + IMAGE_DIRECTORY);
if (!wallpaperDirectory.exists()) { // have the object build the directory structure, if needed.
wallpaperDirectory.mkdirs();
}
try {
File f = new File(wallpaperDirectory, Calendar.getInstance().getTimeInMillis() + ".jpg");
f.createNewFile();
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
MediaScannerConnection.scanFile(this,
new String[]{f.getPath()},
new String[]{"image/jpeg"}, null);
fo.close();
Log.d("TAG", "File Saved::--->" + f.getAbsolutePath());
return f.getAbsolutePath();
} catch (IOException e1) {
e1.printStackTrace();
}
return "";
}
許可をリクエスト
private void requestMultiplePermissions() {
Dexter.withActivity(this)
.withPermissions(
Manifest.permission.CAMERA,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE)
.withListener(new MultiplePermissionsListener() {
@Override
public void onPermissionsChecked(MultiplePermissionsReport report) {
if (report.areAllPermissionsGranted()) { // check if all permissions are granted
Toast.makeText(getApplicationContext(), "All permissions are granted by user!", Toast.LENGTH_SHORT).show();
}
if (report.isAnyPermissionPermanentlyDenied()) { // check for permanent denial of any permission
// show alert dialog navigating to Settings
//openSettingsDialog();
}
}
@Override
public void onPermissionRationaleShouldBeShown(List<PermissionRequest> permissions, PermissionToken token) {
token.continuePermissionRequest();
}
}).
withErrorListener(new PermissionRequestErrorListener() {
@Override
public void onError(DexterError error) {
Toast.makeText(getApplicationContext(), "Some Error! ", Toast.LENGTH_SHORT).show();
}
})
.onSameThread()
.check();
}
これが完全なコードです。
package com.example.cameraa;
import Android.app.Activity;
import Android.content.Intent;
import Android.graphics.Bitmap;
import Android.net.Uri;
import Android.os.Bundle;
import Android.view.View;
import Android.widget.Button;
import Android.widget.ImageView;
public class MainActivity extends Activity {
Button btnTackPic;
Uri photoPath;
ImageView ivThumbnailPhoto;
static int TAKE_PICTURE = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Get reference to views
btnTackPic = (Button) findViewById(R.id.bt1);
ivThumbnailPhoto = (ImageView) findViewById(R.id.imageView1);
btnTackPic.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent cameraIntent = new Intent(Android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, TAKE_PICTURE);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == TAKE_PICTURE && resultCode == RESULT_OK) {
Bitmap photo = (Bitmap)intent.getExtras().get("data");
ivThumbnailPhoto.setImageBitmap(photo);
ivThumbnailPhoto.setVisibility(View.VISIBLE);
}
}
}
カメラの権限も忘れずに追加してください。
ギャラリーまたはカメラから画像を選択するオプションを含むダイアログを作成しました。コールバックとして
ファイルを作成し、ギャラリーから画像を読み取るときに外部ストアを作成する必要があるため、最初にAndroidManifestで権限を定義します
<uses-permission Android:name="Android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission Android:name="Android.permission.READ_EXTERNAL_STORAGE" />
App/src/main/res/xml/file_paths.xmlにfile_paths xmlを作成します
パスあり
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:Android="http://schemas.Android.com/apk/res/Android">
<external-path name="external_files" path="."/>
</paths>
次に、外部ストレージに保存されたファイルにアクセスするためのContent uriを生成するためのファイルプロバイダーを定義する必要があります
<provider
Android:name="androidx.core.content.FileProvider"
Android:authorities="${applicationId}.provider"
Android:exported="false"
Android:grantUriPermissions="true">
<meta-data
Android:name="Android.support.FILE_PROVIDER_PATHS"
Android:resource="@xml/file_paths" />
</provider>
Dailog Layout
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:Android="http://schemas.Android.com/apk/res/Android"
xmlns:app="http://schemas.Android.com/apk/res-auto"
xmlns:tools="http://schemas.Android.com/tools"
Android:layout_width="match_parent"
Android:layout_height="wrap_content">
<androidx.constraintlayout.widget.Guideline
Android:id="@+id/guideline2"
Android:layout_width="wrap_content"
Android:layout_height="wrap_content"
Android:orientation="vertical"
app:layout_constraintGuide_percent="0.50" />
<ImageView
Android:id="@+id/gallery"
Android:layout_width="48dp"
Android:layout_height="48dp"
Android:layout_marginStart="8dp"
Android:layout_marginTop="32dp"
Android:layout_marginEnd="8dp"
Android:layout_marginBottom="32dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="@+id/guideline2"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="@drawable/ic_menu_gallery" />
<ImageView
Android:id="@+id/camera"
Android:layout_width="48dp"
Android:layout_height="0dp"
Android:layout_marginStart="8dp"
Android:layout_marginTop="32dp"
Android:layout_marginEnd="8dp"
Android:layout_marginBottom="32dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="@+id/guideline2"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="@drawable/ic_menu_camera" />
</androidx.constraintlayout.widget.ConstraintLayout>
ImagePicker Dailog
public class ImagePicker extends BottomSheetDialogFragment {
ImagePicker.GetImage getImage;
publ` enter code here` ic ImagePicker(ImagePicker.GetImage getImage, boolean allowMultiple) {
this.getImage = getImage;
}
File cameraImage;@
Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.bottom_sheet_imagepicker, container, false);
view.findViewById(R.id.camera).setOnClickListener(new View.OnClickListener() {@
Override
public void onClick(View view) {
if(ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[] {
Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE
}, 2000);
} else {
captureFromCamera();
}
}
});
view.findViewById(R.id.gallery).setOnClickListener(new View.OnClickListener() {@
Override
public void onClick(View view) {
if(ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[] {
Manifest.permission.READ_EXTERNAL_STORAGE
}, 2000);
} else {
startGallery();
}
}
});
return view;
}
public interface GetImage {
void setGalleryImage(Uri imageUri);
void setCameraImage(String filePath);
void setImageFile(File file);
}@
Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == Activity.RESULT_OK) {
if(requestCode == 1000) {
Uri returnUri = data.getData();
getImage.setGalleryImage(returnUri);
Bitmap bitmapImage = null;
}
if(requestCode == 1002) {
if(cameraImage != null) {
getImage.setImageFile(cameraImage);
}
getImage.setCameraImage(cameraFilePath);
}
}
}
private void startGallery() {
Intent cameraIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
cameraIntent.setType("image/*");
if(cameraIntent.resolveActivity(getActivity().getPackageManager()) != null) {
startActivityForResult(cameraIntent, 1000);
}
}
private String cameraFilePath;
private File createImageFile() throws IOException {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM), "Camera");
File image = File.createTempFile(imageFileName, /* prefix */ ".jpg", /* suffix */ storageDir /* directory */ );
cameraFilePath = "file://" + image.getAbsolutePath();
cameraImage = image;
return image;
}
private void captureFromCamera() {
try {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, FileProvider.getUriForFile(getContext(), BuildConfig.APPLICATION_ID + ".provider", createImageFile()));
startActivityForResult(intent, 1002);
} catch(IOException ex) {
ex.printStackTrace();
}
}
}
このようなアクティビティまたはフラグメントの呼び出しフラグメント/アクティビティのImagePickerの定義
ImagePicker imagePicker;
次に、ボタンをクリックしてdailogを呼び出します
imagePicker = new ImagePicker(new ImagePicker.GetImage() {
@Override
public void setGalleryImage(Uri imageUri) {
Log.i("ImageURI", imageUri + "");
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContext().getContentResolver().query(imageUri, filePathColumn, null, null, null);
assert cursor != null;
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
mediaPath = cursor.getString(columnIndex);
// Set the Image in ImageView for Previewing the Media
imagePreview.setImageBitmap(BitmapFactory.decodeFile(mediaPath));
cursor.close();
}
@Override
public void setCameraImage(String filePath) {
mediaPath =filePath;
Glide.with(getContext()).load(filePath).into(imagePreview);
}
@Override
public void setImageFile(File file) {
cameraImage = file;
}
}, true);
imagePicker.show(getActivity().getSupportFragmentManager(), imagePicker.getTag());
このコードを使用してリスナーをonClickできます(ImageViewまたはボタンを使用できます)
image.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);
}
}
});
ImageViewに表示するには
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
bitmap = (Bitmap) extras.get("data");
image.setImageBitmap(bitmap);
}
}
注:これをマニフェストに挿入します
<uses-feature Android:name="Android.hardware.camera" Android:required="true" />
次のコードを使用して、モバイルカメラを使って写真をキャプチャします。あなたがLolipopよりも高いバージョンを持っているAndroidを使用しているならば、あなたは同じく許可要求を加えるべきです。
private void cameraIntent()
{
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
}
@override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == Activity.RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
}
}