2017-04-20 11 views
-2

カメラで撮影し、その画像(カメラで撮影)をファイアベースのストレージにアップロードしたいと考えています。私はこれに関連する多くの質問を研究しましたが、それは私には意味をなさない。ここに私のコードです。カメラを使用してファイアベースに画像を保存しても動作しない

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

私はBASE64にURIを変換する必要がありますが、私はどんな提案または何Iの変化が、私はこのコードで作成する必要がないことを行うことができないということを聞きました。

+0

意味が分からない –

+0

あなたが探している感覚がわかりません。 –

+0

[去年のI/Oでの私の話](https://www.youtube.com/watch?v=xAsvwy1-oxE)からこのコードをご覧ください:https://gist.github.com/puf/f49a1b07e92952b44f2dc36d9af04e3c#file -mactactivity-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を使用してfirebaseにあなたの画像を保存することができます)。

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

関連する問題