代码之家  ›  专栏  ›  技术社区  ›  Werokk

将图像上载到firebase存储

  •  1
  • Werokk  · 技术社区  · 8 年前

    我正在尝试将从相机拍摄的图像上载到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();
                    }
                } );
    
    
    
                                    }
    
                }
    
    
            }}
    
    2 回复  |  直到 8 年前
        1
  •  1
  •   Mobile Team ADR-Flutter    8 年前

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

    删除上述代码中不需要的代码。。

        2
  •  0
  •   Soon Santos    8 年前

    关于使用用户名返回图像, 我会将照片上传到存储中,并附上以下内容 路径 :

    // storage/photos/users/userID/photoName
    StorageReference storageReference = FirebaseStorage
                                       .getInstanace().getReference
                                       .child("photos/users/" + user_id +  "/photoName");
    

    然后我会创建一个 照片节点 在数据库中,我将添加 用户ID 然后是照片。诸如此类: 在这种情况下,我将用户的个人资料照片存储到数据库中。ProfilePhoto模型只是配置文件图像url。

    ProfilePhoto profilePhoto = new ProfilePhoto(profile_img_url);
    myRef.child("photos").child(user_id).child("photoName").setValue(profile_img_url);
    

    这样,当我想要一些用户的照片时,我只需要从指定用户ID的数据库中获取链接。

    推荐文章