2017-04-20 78 views
-2

我想用相机拍摄照片,然后想要将该照片(用相机拍摄)上传到firebase存储。我研究了许多与此相关的问题,但这对我没有任何意义。这是我的代码。使用相机并将图像保存到firebase不起作用

package com.ivtech.shah.yunas.fireapp; 
import android.app.ProgressDialog; 
import android.content.Intent; 
import android.graphics.Bitmap; 
import android.net.Uri; 
import android.provider.MediaStore; 
android.support.v7.app.AppCompatActivity; 
import android.os.Bundle; 
import android.text.TextUtils; 
import android.view.View; 
import android.widget.Button; 
import android.widget.EditText; 
import android.widget.ImageButton; 
import android.widget.ImageView; 
import android.widget.Toast; 
import com.google.android.gms.tasks.OnSuccessListener; 
import com.google.firebase.auth.FirebaseAuth; 
import com.google.firebase.database.DatabaseReference; 
import com.google.firebase.database.FirebaseDatabase; 
import com.google.firebase.storage.FirebaseStorage; 
import com.google.firebase.storage.StorageReference; 
import com.google.firebase.storage.UploadTask; 

public class ActivityCamera extends AppCompatActivity { 

private static final int CAMERA_REQUEST_CODE=1; 

private static final int GALLERY_REQUEST = 2; 
Bitmap imageBitmap = null; 
private ImageButton takepic; 
private EditText mDescription; 
private Button mSavebtn; 
private ProgressDialog mProgress; 
private StorageReference mStorage; 
private DatabaseReference mDatabase; 
private Uri imageUri=null; 
private FirebaseAuth mAuth; 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_camera); 
    takepic= (ImageButton) findViewById(R.id.imagebtntotakepic); 
    mDescription = (EditText) findViewById(R.id.editTextCameraDesc); 
    mSavebtn= (Button) findViewById(R.id.btnstartsaving); 
     mProgress= new ProgressDialog(this); 

    mAuth = FirebaseAuth.getInstance(); 
    mStorage= FirebaseStorage.getInstance().getReference(); 
    mDatabase = FirebaseDatabase.getInstance().getReference().child("UsersData"); 



    takepic.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 



     } 
    }); 
    mSavebtn.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      startSaving(); 
     } 
    }); 



} 
// Save button funtion 
private void startSaving() { 
    mProgress.setMessage("Uploading Your Data.."); 

    final String descrition_txt =mDescription.getText().toString().trim(); 
    if (!TextUtils.isEmpty(descrition_txt) && imageBitmap!=null){ 
     mProgress.show(); 
     StorageReference filepath= mStorage.child("Saved_Images").child(imageUri.getLastPathSegment()); 
     filepath.putFile(imageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() { 
      @Override 
      public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) { 
      Toast.makeText(ActivityCamera.this,"Uploading Finished!",Toast.LENGTH_LONG).show(); 

      } 
     }) ; 
     mProgress.dismiss(); 


    } 
} 
@Override 
protected void onStart() { 
    if (imageBitmap==null) { 
     Intent intent= new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 
     startActivityForResult(intent,CAMERA_REQUEST_CODE); 
    } 

    super.onStart(); 
} 

@Override 
protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
    super.onActivityResult(requestCode, resultCode, data); 
    if (requestCode==CAMERA_REQUEST_CODE && resultCode==RESULT_OK){ 
     Bundle extras = data.getExtras(); 
     imageBitmap = (Bitmap) extras.get("data"); 
     takepic.setImageBitmap(imageBitmap); 
// Actually this uri is null, im confuse in this 

     Uri imageuri= data.getData(); 
     takepic.setImageURI(imageuri); 


     StorageReference filepath= mStorage.child("Saved_Images").child(imageUri.getLastPathSegment()); 
     filepath.putFile(imageuri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() { 
      @Override 
      public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) { 

       String user_id = mAuth.getInstance().getCurrentUser().getUid(); 

       Uri downloadUrl = taskSnapshot.getDownloadUrl(); 
       //DatabaseReference newPost = mDatabase.child(user_id).push(); 
       DatabaseReference newPost = mDatabase.push(); 
       // newPost.child("title").setValue(title_txt); 

       newPost.child("image").setValue(downloadUrl.toString()); 


       Toast.makeText(ActivityCamera.this, "worked ", Toast.LENGTH_SHORT).show(); 
      } 
     }); 
     }} 
} 

听说我需要的URI转换为Base64,但我不能这样做,任何建议或什么,我的变化,我需要在此代码做。

+0

这没有任何意义先生 –

+0

我不知道在什么意义上,你所期待的。 –

+0

请参阅[我们去年在I/O上的演讲]的代码(https://www.youtube.com/watch?v=xAsvwy1-oxE):https://gist.github.com/puf/f49a1b07e92952b44f2dc36d9af04e3c#file -mainactivity-java-L162 –

回答

0

如果你想捕捉图片并将该图片上传到firebase,那么我希望这段代码能帮到你。

protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_photo); 
    intent = getIntent(); 
    user = FirebaseAuth.getInstance().getCurrentUser(); 
    getUserToken(); 

    database = FirebaseDatabase.getInstance(); 
    myDBRef = database.getReference("profile"); 
    mStorage = FirebaseStorage.getInstance().getReference().child("profile_photo").child(userUid); 
    mProgressDialog = new ProgressDialog(this); 
    selectedIV = (ImageView)findViewById(R.id.selected_imageView); 
    uploadButton = (Button)findViewById(R.id.upload_button); 
    uploadButton.setVisibility(View.GONE); 
    fromCamera = (Button)findViewById(R.id.from_camera_button); 
    fromCamera.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View view) { 
      try { 
       // use standard intent to capture an image 
       Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 

       File direct = new File(Environment.getExternalStorageDirectory() + "/perfectDatingProfile"); 
       if (!direct.exists()) { 
        File wallpaperDirectory = new File(Environment.getExternalStorageDirectory() + "/perfectDatingProfile"); 
        wallpaperDirectory.mkdirs(); 
       } 
       destination = Uri.fromFile(new File(Environment.getExternalStorageDirectory()+"/perfectDatingProfile", "cropped.png")); 
       captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, destination); 

       startActivityForResult(captureIntent, 1); 
      } catch (ActivityNotFoundException anfe) { 
      } 
     } 
    }); 
    laterButton = (Button)findViewById(R.id.later_button); 
    uploadButton.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      uploadPicture(); 
     } 
    }); 
    myRef = FirebaseDatabase.getInstance().getReference(); 
    selectImageButton = (Button) findViewById(R.id.select_photo_button); 

    laterButton.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View view) { 
      String userName = intent.getExtras().getString("userName"); 
      String sex = intent.getExtras().getString("sex"); 
      String uid = intent.getExtras().getString("uid"); 
      Integer year = intent.getExtras().getInt("year"); 
      Integer month = intent.getExtras().getInt("month"); 
      Integer dayOfMonth = intent.getExtras().getInt("dayOfMonth"); 
      Double latitude = intent.getExtras().getDouble("latitude"); 
      Double longitude = intent.getExtras().getDouble("longitude"); 
      userObj = new ProfileModel(userName,sex,uid,year,month,dayOfMonth,latitude,longitude,"none", "none"); 
      myRef.child("profile").child(userObj.getUid()).setValue(userObj); 
      startActivity(new Intent(PhotoActivity.this,BaseActivity.class)); 
     } 
    }); 
    if(intent.getExtras() == null){ 
     laterButton.setVisibility(View.GONE); 
    } 
    selectImageButton.setOnClickListener(new View.OnClickListener(){ 
     @Override 
     public void onClick(View v) { 
      Intent cropIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI); 
      cropIntent.putExtra("crop","true"); 
      cropIntent.putExtra("aspectX",1); 
      cropIntent.putExtra("aspectY",1); 
      cropIntent.putExtra("return-data",false); 
      Log.d("------",Environment.getExternalStorageDirectory().toString()); 
      File direct = new File(Environment.getExternalStorageDirectory() + "/perfectDatingProfile"); 
      if (!direct.exists()) { 
       File wallpaperDirectory = new File(Environment.getExternalStorageDirectory() + "/perfectDatingProfile"); 
       wallpaperDirectory.mkdirs(); 
      } 
      destination = Uri.fromFile(new File(Environment.getExternalStorageDirectory()+"/perfectDatingProfile", "cropped.png")); 
      cropIntent.putExtra(MediaStore.EXTRA_OUTPUT, destination); 
      startActivityForResult(cropIntent, 2); 
     } 
    }); 
    ProfileModel sharedModel = getPreferences(); 
    if (sharedModel !=null){ 
     Bitmap bitmap = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory() + "/perfectDatingProfile/profile.jpg"); 
     selectedIV.setImageBitmap(bitmap); 
    } 
} 

之后,你可以保存你的形象在你的SD卡:

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

    if (requestCode == GALLEY_INTENT && resultCode == RESULT_OK){ 
     selectedIV.setImageURI(destination); 
     imageFile = new File(destination.getPath()); 
     uploadButton.setVisibility(View.VISIBLE); 
     toastFilesize(); 
     Bitmap bigProfile = BitmapFactory.decodeFile(destination.getPath()); 
     smallProfile = Bitmap.createScaledBitmap(bigProfile,250,250,false); 
     bitmapToFile(smallProfile,"smallProfile"); 
    }else if (requestCode == 1 && resultCode == RESULT_OK){ 
     selectedIV.setImageURI(destination); 
     imageFile = new File(destination.getPath()); 
     uploadButton.setVisibility(View.VISIBLE); 
     toastFilesize(); 
     Bitmap bigProfile = BitmapFactory.decodeFile(destination.getPath()); 
     smallProfile = Bitmap.createScaledBitmap(bigProfile,250,250,false); 
     bitmapToFile(smallProfile,"smallProfile"); 
    } 
} 

private void toastFilesize(){ 
    Cursor returnCursor = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, null, null, null, null); 
    int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME); 
    int sizeIndex = returnCursor.getColumnIndex(OpenableColumns.SIZE); 
    returnCursor.moveToFirst(); 
    Toast.makeText(PhotoActivity.this,Long.toString(returnCursor.getLong(sizeIndex)),Toast.LENGTH_LONG).show(); 
} 
private void bitmapToFile(Bitmap bitmap, String name) { 
    smallImageFile = new File(Environment.getExternalStorageDirectory()+"/perfectDatingProfile", "small.jpg"); 

    OutputStream os; 
    try { 
     os = new FileOutputStream(smallImageFile); 
     bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os); 
     os.flush(); 
     os.close(); 
     Log.d("------",imageFile.getAbsolutePath().toString()); 
    } catch (Exception e) { 
     Log.e(getClass().getSimpleName(), "Error writing bitmap", e); 
    } 
} 

现在你可以使用uploadfpicture上火力存储图像();

private void uploadPicture(){ 

    StorageReference filepath = mStorage.child("profile"); 

    mProgressDialog.setMessage("Uploading....."); 
    mProgressDialog.show(); 

    filepath.child("small").putFile(Uri.fromFile(smallImageFile)).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() { 
     @Override 
     public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) { 
      Uri downloadUri = taskSnapshot.getDownloadUrl(); 
      Log.d("2112","success upload small file" + userUid); 
     } 
    }).addOnFailureListener(new OnFailureListener() { 
     @Override 
     public void onFailure(@NonNull Exception e) { 
      Toast.makeText(PhotoActivity.this,"Upload Failed..",Toast.LENGTH_LONG).show(); 
     } 
    }); 

    filepath.putFile(Uri.fromFile(imageFile)).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() { 
     @Override 
     public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) { 
      downloadUri = taskSnapshot.getDownloadUrl(); 
      storeToLocal(); 

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

private void getUserToken(){ 
    if (user != null) { 
     userUid = user.getUid(); 

    } 
} 

private void storeToLocal(){ 
    islandRef = mStorage.child("profile"); 
    try { 
     localFile = File.createTempFile("images", "jpg"); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
    islandRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() { 
     @Override 
     public void onSuccess(Uri uri) { 
      downloadUri = uri; 
      islandRef.child("small").getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() { 
       @Override 
       public void onSuccess(Uri uri) { 
        smallUri = uri; 
        uploadUserObj(); 
       } 
      }).addOnFailureListener(new OnFailureListener() { 
       @Override 
       public void onFailure(@NonNull Exception exception) { 

       } 
      }); 

     } 
    }).addOnFailureListener(new OnFailureListener() { 
     @Override 
     public void onFailure(@NonNull Exception exception) { 

     } 
    }); 
} 

private ProfileModel getPreferences(){ 
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); 
    Gson gson = new Gson(); 
    String json = preferences.getString("myProfile", ""); 
    ProfileModel obj = gson.fromJson(json, ProfileModel.class); 

    return obj; 
} 
private void uploadUserObj(){ 
    if(intent.getExtras() == null){ 
     ProfileModel sharedModel = getPreferences(); 
     sharedModel.setPhotoUrl(downloadUri.toString()); 
     sharedModel.setSmallProfileUri(smallUri.toString()); 
     myRef.child("profile").child(sharedModel.getUid()).setValue(sharedModel); 

     Log.d("------","from other activity"); 

    }else { 
     Log.d("------","from profile activity"); 
     String userName = intent.getExtras().getString("userName"); 
     String sex = intent.getExtras().getString("sex"); 
     String uid = intent.getExtras().getString("uid"); 
     Integer year = intent.getExtras().getInt("year"); 
     Integer month = intent.getExtras().getInt("month"); 
     Integer dayOfMonth = intent.getExtras().getInt("dayOfMonth"); 
     Double latitude = intent.getExtras().getDouble("latitude"); 
     Double longitude = intent.getExtras().getDouble("longitude"); 

     userObj = new ProfileModel(userName,sex,uid,year,month,dayOfMonth,latitude,longitude,downloadUri.toString(), smallUri.toString()); 
     myRef.child("profile").child(userObj.getUid()).setValue(userObj); 
    } 

    islandRef.getFile(localFile).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() { 
     @Override 
     public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) { 
      bitmapServer = BitmapFactory.decodeFile(localFile.getAbsolutePath()); 
      createDirectoryAndSaveFile(bitmapServer,"profile.jpg"); 
      mProgressDialog.dismiss(); 
     } 
    }).addOnFailureListener(new OnFailureListener() { 
     @Override 
     public void onFailure(@NonNull Exception exception) { 
      mProgressDialog.dismiss(); 

     } 
    }); 
} 

private void createDirectoryAndSaveFile(Bitmap imageToSave, String fileName) { 
    File direct = new File(Environment.getExternalStorageDirectory() + "/perfectDatingProfile"); 

    if (!direct.exists()) { 

     File wallpaperDirectory = new File(Environment.getExternalStorageDirectory() + "/perfectDatingProfile"); 
     wallpaperDirectory.mkdirs(); 
    } 

    File file = new File(new File(Environment.getExternalStorageDirectory() + "/perfectDatingProfile"), fileName); 
    if (file.exists()) { 
     file.delete(); 
    } 
    try { 
     FileOutputStream out = new FileOutputStream(file); 
     imageToSave.compress(Bitmap.CompressFormat.JPEG, 100, out); 
     out.flush(); 
     out.close(); 

     startActivity(new Intent(PhotoActivity.this,BaseActivity.class)); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
} 


public Bitmap getBitmapFromURL(String imageUrl) { 
    try { 
     URL url = new URL(imageUrl); 
     HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 
     connection.setDoInput(true); 
     connection.connect(); 
     InputStream input = connection.getInputStream(); 
     Bitmap myBitmap = BitmapFactory.decodeStream(input); 
     return myBitmap; 
    }catch (IOException e){ 
     e.printStackTrace(); 
     return null; 
    } 
} 
+0

这是一个很大的代码,我可以在它里面找到什么即时通讯 –

+0

你可以使用此代码捕获图像并存储在firebase上。但是如果你只想上传捕获的图像,那么你可以使用uploadUserObj()函数和uploadPicture(); – Chitra

相关问题