イメージをキャプチャしてその画像を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;
}
}
意味が分からない –
あなたが探している感覚がわかりません。 –
[去年のI/Oでの私の話](https://www.youtube.com/watch?v=xAsvwy1-oxE)からこのコードをご覧ください:https://gist.github.com/puf/f49a1b07e92952b44f2dc36d9af04e3c#file -mactactivity-java-L162 –