Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/image/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 安卓:将多媒体资料功能与相机拍摄相结合_Android_Image_Android Camera_Android Gallery - Fatal编程技术网

Android 安卓:将多媒体资料功能与相机拍摄相结合

Android 安卓:将多媒体资料功能与相机拍摄相结合,android,image,android-camera,android-gallery,Android,Image,Android Camera,Android Gallery,我正在做一个Android项目,在这个项目中,我有一个功能,用户可以点击a按钮,它会打开相机上传图像。“上载”按钮将隐藏,直到在预览中拍摄并显示图像 我想做的是使用相同的上传按钮,我现在默认设置为可见,点击它,我想打开一个图库,用户可以使用它选择一个图像,它将显示在预览中 我有一个布尔标志来管理它,如果该标志为false,则打开gallery,否则将上载预览中的图像 我有这个,但我不知道如何打开一个画廊,然后发送图像预览,上传。我是Android编程新手,所以请考虑一下 我搜索了类似的功能,但问

我正在做一个Android项目,在这个项目中,我有一个功能,用户可以点击a
按钮,它会打开相机上传图像。“上载”按钮将隐藏,直到在预览中拍摄并显示图像

我想做的是使用相同的上传按钮,我现在默认设置为可见,点击它,我想打开一个图库,用户可以使用它选择一个图像,它将显示在预览中

我有一个布尔标志来管理它,如果该标志为false,则打开gallery,否则将上载预览中的图像

我有这个,但我不知道如何打开一个画廊,然后发送图像预览,上传。我是Android编程新手,所以请考虑一下

我搜索了类似的功能,但问题是,我没有找到,在哪里集成了这些功能

Java代码:

    RobotoTextView BtnSelectImage;
    private ImageView ImgPhoto;

    CheckBox profilePhotoCheckBox;
    final RestaurantImageServiceImpl restaurantService = new RestaurantImageServiceImpl();

    private static final int CAMERA_PHOTO = 111;
    private Uri imageToUploadUri;

   private static volatile Bitmap reducedSizeBitmap;

    ByteArrayOutputStream stream = new ByteArrayOutputStream();

    private static boolean galleryFlag = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.add_restaurant_images);

  ImgPhoto = (ImageView) findViewById(R.id.userPhotoImageView);
        BtnSelectImage = (RobotoTextView) findViewById(R.id.userPhotoButtonSelect);
        profilePhotoCheckBox = (CheckBox)findViewById(R.id.profilePhotoCheckBox);
        BtnSelectImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    galleryFlag = true;
                    captureCameraImage();

                } catch (Exception e) {
                    Toast.makeText(getApplicationContext(), "Couldn't load photo", Toast.LENGTH_LONG).show();
                }
            }
        });

        uploadImageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!(v == null)) {

                    if(!galleryFlag){
                        // I think the gallery open code should come here. 
                    }

                    if (profilePhotoCheckBox.isChecked()) {
                        uploadImage(true);
                    }else {
                        uploadImage(false);
                    }
                    new AlertDialog.Builder(AddPhotosForRestaurant.this)
                    .setTitle("Add more photos")
                            .setMessage("Are you sure you want to add more photos?")
                            .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    finish();
                                    startActivity(getIntent());
                                }
                            })
                            .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    Intent intent = new Intent(getApplicationContext(), RestaurantMenu.class);
                                    startActivity(intent);
                                    finish();
                                }
                            })
                            .setIcon(android.R.drawable.ic_dialog_alert)
                            .show();

                }
            }
        });

    }

    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;
        }
    }

    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);
    }

    @Override
    public void onBackPressed() {
        Intent intent = new Intent(this, Login.class);
        StaticRestTemplate.setReplyString("");
        StaticRestTemplate.setLoggedInUser("");
        StaticRestTemplate.setJsessionid("");
        startActivity(intent);
        finish();
    }

    @Override
    protected void onActivityResult(final 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);
                reducedSizeBitmap = getBitmap(imageToUploadUri.getPath());
                if(reducedSizeBitmap != null){
                    ImgPhoto.setImageBitmap(reducedSizeBitmap);
                    RobotoTextView uploadImageButton = (RobotoTextView) 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();
            }
        }
    }

    private void uploadImage(boolean profilePhoto) {
        if(!(reducedSizeBitmap == null)){
            if(reducedSizeBitmap == null){
                Log.d("Image bitmap"," Is null");
            }
            reducedSizeBitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
            byte[] byteArray = stream.toByteArray();
            this.restaurantService.addRestaurantImage(byteArray,profilePhoto);
        }
    }
}
我希望这些信息足够了。谁能告诉我应该把哪些函数放在哪里。非常感谢。:-)

带答案编辑

最后,集成起作用了。我必须把收到的答案和收到的答案结合起来。 最终代码


非常感谢您的帮助…-)

以常量文件写入(ActivityConstantUtils.java)

要打开图库并获取所选图像的路径,请使用以下代码:

 Intent photoPickerIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
 photoPickerIntent.setType("image/*");
 photoPickerIntent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());        
 mActPanelFragment.startActivityForResult(photoPickerIntent, ActivityConstantUtils.GALLERY_INTENT_REQUEST_CODE);
然后,在activityResult()方法中获得路径

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
(requestCode == ActivityConstantUtils.GALLERY_INTENT_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
try {
            String imagePath = getFilePath(data);
            // TODO: Here you set data to preview screen
    }catch(Exception e){}
}
}


嗨,谢谢你的回答。我集成了它,但是每次都选择了错误的图片来显示和上传。我已经在主帖子中发布了更新的代码。你能看看我做错了什么吗。谢谢……:)@我们是博格:很抱歉延迟回复。此问题是否已解决或需要检查?是。问题解决了。正如我在评论中提到的,您和链接的答案…-)
 Intent photoPickerIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
 photoPickerIntent.setType("image/*");
 photoPickerIntent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());        
 mActPanelFragment.startActivityForResult(photoPickerIntent, ActivityConstantUtils.GALLERY_INTENT_REQUEST_CODE);
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
(requestCode == ActivityConstantUtils.GALLERY_INTENT_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
try {
            String imagePath = getFilePath(data);
            // TODO: Here you set data to preview screen
    }catch(Exception e){}
}
private String getFilePath(Intent data) {
    String imagePath;
    Uri selectedImage = data.getData();
    String[] filePathColumn = {MediaStore.Images.Media.DATA};

    Cursor cursor = getActivity().getContentResolver().query(selectedImage, filePathColumn, null, null, null);
    cursor.moveToFirst();

    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
    imagePath = cursor.getString(columnIndex);
    cursor.close();

    return imagePath;

}