Androidの解析クラウドサーバーに画像をアップロードしたい。しかし、私はそうすることができません。
私は次のコードを試しました:
Drawable drawable = getResources().getDrawable(R.drawable.profilepic) ;
Bitmap bitmap = (Bitmap)(Bitmap)drawable()
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] data = stream.toByteArray();
ParseFile imageFile = new ParseFile("image.png", data);
imageFile.saveInBackground();
どうすればできるか教えてください。
私はこの一般的な問題のための最高の決定的なコードを見つけるために賞金を追加しました
バックグラウンドでParseObjectを保存する
// ParseObject ParseObject pObject = new ParseObject("ExampleObject"); pObject.put("myNumber", number); pObject.put("myString", name); pObject.saveInBackground(); // asynchronous, no callback
コールバックでバックグラウンドで保存
pObject.saveInBackground(new SaveCallback () { @Override public void done(ParseException ex) { if (ex == null) { isSaved = true; } else { // Failed isSaved = false; } } });
Save ...()メソッドのバリエーションには、次のものがあります。
saveAllinBackground() saves a ParseObject with or without a callback. saveAll(List<ParseObject> objects) saves a list of ParseObjects. saveAllinBackground(List<ParseObject> objects) saves a list of ParseObjects in the background. saveEventually() lets you save a data object to the server at some point in the future; use this method if the Parse cloud is not currently accessible.
ParseObjectがクラウドに正常に保存されると、一意のオブジェクトIDが割り当てられます。このオブジェクトIDは、ParseObjectインスタンスを一意に識別するため、非常に重要です。たとえば、オブジェクトIDを使用して、オブジェクトがクラウドに正常に保存されたかどうかを判断したり、特定のParseオブジェクトインスタンスを取得および更新したり、特定のParseObjectを削除したりします。
あなたがあなたの問題を解決してくれることを願っています。
数時間苦労した後、コードセグメントは私のために動作します。
1。アクティビティクラスのデータメンバー
Bitmap bmp;
Intent i;
Uri BmpFileName = null;
2。カメラの起動。カメラのアクティビティを開始し、ファイルへの参照を保存するBmpFileNameを目標とする
String storageState = Environment.getExternalStorageState();
if (storageState.equals(Environment.MEDIA_MOUNTED)) {
String path = Environment.getExternalStorageDirectory().getName() + File.separatorChar + "Android/data/" + this.getPackageName() + "/files/" + "Doc1" + ".jpg";
File photoFile = new File(path);
try {
if (photoFile.exists() == false) {
photoFile.getParentFile().mkdirs();
photoFile.createNewFile();
}
}
catch (IOException e)
{
Log.e("DocumentActivity", "Could not create file.", e);
}
Log.i("DocumentActivity", path);
BmpFileName = Uri.fromFile(photoFile);
i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
i.putExtra(MediaStore.EXTRA_OUTPUT, BmpFileName);
startActivityForResult(i, 0);
。onActivityResultをオーバーライドしてカメラ出力からコンテンツを読み取る。目標はbmp変数を評価することです。
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
try {
bmp = MediaStore.Images.Media.getBitmap( this.getContentResolver(), BmpFileName);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Myocode to display image on UI - You can ignore
if (bmp != null)
IV.setImageBitmap(bmp);
}
}
4。保存イベント時
// MUST ENSURE THAT YOU INITIALIZE PARSE
Parse.initialize(mContext, "Key1", "Key2");
ParseObject pObj = null;
ParseFile pFile = null ;
pObj = new ParseObject ("Document");
pObj.put("Notes", "Some Value");
// Ensure bmp has value
if (bmp == null || BmpFileName == null) {
Log.d ("Error" , "Problem with image"
return;
}
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(CompressFormat.PNG, 100, stream);
pFile = new ParseFile("DocImage.jpg", stream.toByteArray());
try
{
pFile.save();
pObj.put("FileName", pFile);
pObj.save();
_mParse.DisplayMessage("Image Saved");
}
catch (ParseException e)
{
// TODO Auto-generated catch block
_mParse.DisplayMessage("Error in saving image");
e.printStackTrace();
}
//私の場合はアクティビティを終了します。あなたは他のものを選ぶかもしれませんfinish();
ここに他との主な違いがあります
うまくいかない場合はお知らせください
このように使う
//Convert Bitmap to Byte array --For Saving Image to Parse Db. */
Bitmap profileImage= "your bitmap";
ByteArrayOutputStream blob = new ByteArrayOutputStream();
profileImage.compress(CompressFormat.PNG, 0 /* ignored for PNG */,blob);
imgArray = blob.toByteArray();
//Assign Byte array to ParseFile
parseImagefile = new ParseFile("profile_pic.png", imgArray);
parseUser.getCurrentUser().put("columname in parse db", parseImagefile);
parseUser.getCurrentUser().saveInBackground();
これがお役に立てば幸いです。
Imageuploadの単純なコードとGlideを使用して取得する解析
画像のアップロード
destination_profile
は、画像パスをアップロードするファイルオブジェクトです。
ParseUser currentUser = ParseUser.getCurrentUser();
if (destination_profile != null) {
Glide.with(getActivity()).load(destination_profile.getAbsolutePath()).asBitmap().toBytes().centerCrop().into(new SimpleTarget<byte[]>() {
@Override
public void onResourceReady(byte[] resource, GlideAnimation<? super byte[]> glideAnimation) {
final ParseFile parseFile = new ParseFile(destination_profile.getName(), resource);
parseFile.saveInBackground(new SaveCallback() {
@Override
public void done(ParseException e) {
currentUser.put("picture", parseFile);
currentUser.saveInBackground(new SaveCallback() {
@Override
public void done(ParseException e) {
showToast("Profile image upload success");
}
});
}
});
}
});
}
画像検索
img_userProfilePicture_bg
は、イメージを設定するImageViewのオブジェクトです。
ParseUser currentUser = ParseUser.getCurrentUser();
if (currentUser.has("picture")) {
ParseFile imageFile = (ParseFile) currentUser.get("picture");
imageFile.getDataInBackground(new GetDataCallback() {
public void done(final byte[] data, ParseException e) {
if (e == null) {
Glide.with(getActivity()).load(data).centerCrop().into(img_userProfilePicture_bg);
} else {
// something went wrong
}
}
});
}
Parse.initialize(this, "applicationId", "clientKey");
byte[] data = "Sample".getBytes(); //data of your image file comes here
final ParseFile file = new ParseFile(data);
try {
file.save();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (file.isDirty()){
//exception or error message etc
}
else{
try {
ParseUser.logIn("username", "password"); //skip this if already logged in
} catch (ParseException e2) {
e2.printStackTrace();
}
ParseObject userDisplayImage = new ParseObject("UserDisplayImage");
user = ParseUser.getCurrentUser();
userDisplayImage.put("user", user); //The logged in User
userDisplayImage.put("displayImage", file); //The image saved previously
try {
userDisplayImage.save(); //image and user object saved in a new table. Check data browser
} catch (ParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
//See how to retrieve
ParseQuery query = new ParseQuery("UserDisplayImage");
query.whereEqualTo("user", user);
try {
parseObject = query.getFirst();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ParseFile imageFile = null;
imageFile = parseObject.getParseFile("displayImage");
try {
byte[] imgData = imageFile.getData(); //your image data!!
} catch (ParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
ビットマップファイルbitmap
があるとします。
ParseObject object = new ParseObject("NameOfClass");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] scaledData = stream.toByteArray();
ParseFile image = new ParseFile("image.jpeg",scaledData);
image.saveInBackground(new SaveCallback() {
@Override
public void done(ParseException e) {
if (e==null)
//Image has been saved as a parse file.
else
//Failed to save the image as parse file.
}
});
object.put("images",image);
object.saveInBackground(new SaveCallback() {
@Override
public void done(ParseException e) {
if (e==null)
//Image has been successfuly uploaded to Parse Server.
else
//Error Occured.
}
});
ビットマップをbyte[]
に変換してから、解析オブジェクトに関連付ける前に解析ファイルをアップロードすることが重要です。