Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/229.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
Java 将图像上载到firebase存储_Java_Android_Firebase_Firebase Storage - Fatal编程技术网

Java 将图像上载到firebase存储

Java 将图像上载到firebase存储,java,android,firebase,firebase-storage,Java,Android,Firebase,Firebase Storage,我正试图将从相机拍摄的图像上传到firebase存储,出现一个消息对话框,但它一直在充电,没有图像上传到存储。 另外,我想知道,我怎样才能从特定用户那里获得发送的图像?我是否应该将图像的用户名赋予图像,这样我就可以用他的名字取回图像 public class ProfileActivity extends AppCompatActivity { public static final int CAMERA_REQUEST = 10; private LocationService

我正试图将从相机拍摄的图像上传到firebase存储,出现一个消息对话框,但它一直在充电,没有图像上传到存储。 另外,我想知道,我怎样才能从特定用户那里获得发送的图像?我是否应该将图像的用户名赋予图像,这样我就可以用他的名字取回图像

public class ProfileActivity extends AppCompatActivity {
    public static final int CAMERA_REQUEST = 10;
    private LocationService service;
    private Button uploadbtn;
    private ImageView imgSpecimentPhoto;
    private ImageView imgSpecimentPhoto2;
    private ImageView imgSpecimentPhoto3;
    private StorageReference storage;
    private ProgressDialog mProgress;
    Uri photoURI;
    String mCurrentPhotoPath;
    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 = getExternalFilesDir( Environment.DIRECTORY_PICTURES );
        File image = File.createTempFile(
                imageFileName,
                ".jpg",
                storageDir
        );
        mCurrentPhotoPath = image.getAbsolutePath();
        return image;
    }
    private void dispatchTakePictureIntent(){
        Intent takePictureIntent = new Intent (MediaStore.ACTION_IMAGE_CAPTURE);
        if(takePictureIntent.resolveActivity( getPackageManager())!= null){
            //Create the file where the photo should go
            File photoFile = null;
            try{
                photoFile = createImageFile();
            }catch (IOException ex){
                System.out.println("error taking the pic");
            }
            //Continue only if the file was successfull
            if(photoFile != null){
                photoURI = FileProvider.getUriForFile( this, "com.example.android.fileprovider",photoFile);
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
                startActivityForResult( takePictureIntent, CAMERA_REQUEST );
            }
        }
    }


    private View currentView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_profile );
        service = new LocationService(this);
        uploadbtn = (Button) findViewById(R.id.upload);
        storage = FirebaseStorage.getInstance().getReference();
        mProgress = new ProgressDialog( this );

        //get access to the image view
        imgSpecimentPhoto = findViewById(R.id.camerabtn);
        imgSpecimentPhoto2 = findViewById(R.id.camerabtn5 );
        imgSpecimentPhoto3 = findViewById(R.id.camerabtn6);


        uploadbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mProgress.setMessage("Uploading...");
                mProgress.show();
                dispatchTakePictureIntent();


                    }
                } );



            }


    public void checkPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED ||
                ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED
                ) {//Can add more as per requirement

            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION},
                    123);
        }
    }

    public void btnTakePhotoClicked(View v) {
        Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(cameraIntent, CAMERA_REQUEST);
        System.out.println("first");
        currentView= v;

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        photoURI = data.getData();


        //did the user chose okay
        if(requestCode == CAMERA_REQUEST && resultCode == RESULT_OK){

            //we are hearing back grom the camera
            Bitmap cameraImage = (Bitmap) data.getExtras().get( "data" );
            //now we have the image
            ImageView cur = (ImageView) currentView;
            cur.setImageBitmap( cameraImage );
            if (cur.getId() == imgSpecimentPhoto.getId()) {
                imgSpecimentPhoto2.setVisibility( View.VISIBLE );
            }
            if (cur.getId() == imgSpecimentPhoto2.getId()) {
                imgSpecimentPhoto3.setVisibility( View.VISIBLE );

            StorageReference filepath = storage.child("Photos").child( photoURI.getLastPathSegment());
            filepath.putFile( photoURI).addOnSuccessListener( new OnSuccessListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                    Toast.makeText(ProfileActivity.this, "Upload Successfull", Toast.LENGTH_SHORT).show();
                    mProgress.dismiss();

                }
            } ).addOnFailureListener( new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    Toast.makeText( ProfileActivity.this, "Upload Failed", Toast.LENGTH_SHORT).show();
                }
            } );



                                }

            }


        }}
public class ProfileActivity扩展了AppCompative活动{
公共静态最终int摄像机_请求=10;
私人定位服务;
专用按钮上传;
私人图像查看imgSpecimentPhoto;
私有ImageView imgSpecimentPhoto2;
private ImageView imgSpecimentPhoto3;
私有存储参考存储;
私人进程;
Uri-photoURI;
串电流光路;
私有文件createImageFile()引发IOException{
//创建图像文件名
字符串时间戳=新的SimpleDateFormat(“yyyyMMdd_HHmmss”)。格式(新日期();
字符串imageFileName=“JPEG”+时间戳+”;
File storageDir=getExternalFilesDir(Environment.DIRECTORY\u图片);
File image=File.createTempFile(
imageFileName,
“.jpg”,
storageDir
);
mCurrentPhotoPath=image.getAbsolutePath();
返回图像;
}
私有无效DispatchTakePictureContent(){
Intent takePictureIntent=新的意图(MediaStore.ACTION\u IMAGE\u CAPTURE);
if(takePictureContent.resolveActivity(getPackageManager())!=null){
//创建照片应该放在哪里的文件
文件photoFile=null;
试一试{
photoFile=createImageFile();
}捕获(IOEX异常){
System.out.println(“获取pic时出错”);
}
//仅当文件成功时才继续
if(photoFile!=null){
photoURI=FileProvider.getUriForFile(这是“com.example.android.FileProvider”,photoFile);
takePictureContent.putExtra(MediaStore.EXTRA_输出,photoURI);
startActivityForResult(拍摄图片内容、摄像头请求);
}
}
}
私有视图currentView;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
服务=新位置服务(本);
uploadbtn=(按钮)findViewById(R.id.upload);
storage=FirebaseStorage.getInstance().getReference();
mpprogress=新建进度对话框(此对话框);
//获取图像视图的访问权限
imgSpecimentPhoto=findviewbyd(R.id.camerabtn);
imgSpecimentPhoto2=findViewById(R.id.camerabtn5);
imgSpecimentPhoto3=findViewById(R.id.camerabtn6);
uploadbtn.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图v){
设置消息(“上传…”);
mProgress.show();
DispatchTakePictureContent();
}
} );
}
公共无效检查权限(){
if(ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS\u FINE\u LOCATION)!=PackageManager.permission\u已授予||
ContextCompat.checkSelfPermission(此,Manifest.permission.ACCESS\u位置)!=PackageManager.permission\u已授予
){//可以根据需要添加更多
ActivityCompat.requestPermissions(此,
新字符串[]{Manifest.permission.ACCESS\u FINE\u LOCATION,Manifest.permission.ACCESS\u rough\u LOCATION},
123);
}
}
公共无效BtntakePhotoclick(视图v){
Intent cameraIntent=新的Intent(MediaStore.ACTION\u IMAGE\u CAPTURE);
startActivityForResult(摄像机帐篷、摄像机请求);
System.out.println(“第一”);
currentView=v;
}
@凌驾
受保护的void onActivityResult(int请求代码、int结果代码、意图数据){
super.onActivityResult(请求代码、结果代码、数据);
photoURI=data.getData();
//用户选择OK了吗
if(requestCode==CAMERA\u请求和&resultCode==RESULT\u确定){
//我们听到了格罗姆对摄像机的回音
位图cameraImage=(位图)data.getExtras().get(“数据”);
//现在我们有了图像
ImageView cur=(ImageView)currentView;
当前设置图像位图(cameraImage);
if(cur.getId()==imgSpecimentPhoto.getId()){
imgSpecimentPhoto2.setVisibility(View.VISIBLE);
}
if(cur.getId()==imgSpecimentPhoto2.getId()){
imgSpecimentPhoto3.setVisibility(View.VISIBLE);
StorageReference文件路径=storage.child(“照片”).child(photoURI.getLastPathSegment());
filepath.putFile(photoURI).addOnSuccessListener(新的OnSuccessListener()){
@凌驾
成功时公共无效(UploadTask.TaskSnapshot TaskSnapshot){
Toast.makeText(ProfileActivity.this,“上载成功”,Toast.LENGTH_SHORT.show();
mProgress.disclose();
}
}).addOnFailureListener(新的OnFailureListener(){
@凌驾
public void onFailure(@NonNull异常e){
Toast.makeText(ProfileActivity.this,“上载失败”,Toast.LENGTH_SHORT.show();
}
} );
}
}
}}

在Firebase上上载图像时使用下面的代码

   bearImage.setDrawingCacheEnabled(true);
    bearImage.buildDrawingCache();
    Bitmap bitmap = bearImage.getDrawingCache();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
    byte[] data = baos.toByteArray();

    // Upload it to our reference
    UploadTask uploadTask = bearRef.putBytes(data);
    buttonDownload.setEnabled(false);
    uploadTask.addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception exception) {
            // Handle unsuccessful uploads
            progressDialog.dismiss();

            Log.w(LOG_TAG, "Upload failed: " + exception.getMessage());
        }
    }).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
        @Override
        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
            // taskSnapshot.getMetadata() contains file metadata such as size, content-type, and download URL.
            Uri downloadUrl = taskSnapshot.getDownloadUrl();
            progressDialog.dismiss();

            Log.d(LOG_TAG, "Download Url: " + downloadUrl);
            buttonDownload.setEnabled(true);
        }
    });
bearImage.setDrawingCacheEnabled(true);
bearImage.buildDrawingCache();
位图Bitmap=bearImage.getDrawingCache();
ByteArrayOutputStream bas=新的ByteArrayOutputStream();
压缩(bitmap.CompressFormat.JPEG,100,baos);
字节[]数据=baos.toByteArray();
//上传到我们的参考
// storage/photos/users/userID/photoName
StorageReference storageReference = FirebaseStorage
                                   .getInstanace().getReference
                                   .child("photos/users/" + user_id +  "/photoName");
ProfilePhoto profilePhoto = new ProfilePhoto(profile_img_url);
myRef.child("photos").child(user_id).child("photoName").setValue(profile_img_url);