gpt4 book ai didi

android - 图像未从 android 插入到 MySQL

转载 作者:行者123 更新时间:2023-11-28 23:38:13 25 4
gpt4 key购买 nike

我真的需要帮助!!

我使用下面的代码从图库中获取图像,最后通过 php 将其插入到 MySQL 中。图片将从Activity B获取,点击Activity A中的按钮后返回到Activity A并保存到MySQL中。

Activity B

 Uri selectedImage;
private Uri imageUri;
ImageView imageView;

private void activeGallery() {
Intent intent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
startActivityForResult(intent, RESULT_LOAD_IMAGE);
}


@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case RESULT_LOAD_IMAGE:
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK & null != data) {
selectedImage = data.getData();
imageView.setImageURI(selectedImage);
}

break;

submit.setOnClickListener(new View.OnClickListener() { // back to Activity A
@Override
public void onClick(View v) {
Intent returnIntent = new Intent();
amount = Amount.getText().toString();
description = Description.getText().toString();
type = spinnerType.getSelectedItem().toString();
returnIntent.putExtra("type", type);
returnIntent.putExtra("description", description);
returnIntent.putExtra("amount", amount);
if(selectedImage!=null) {
returnIntent.putExtra("img_uri", selectedImage.toString());
}
else
{
returnIntent.putExtra("img_uri", Uri.parse("android.resource://com.example.project.myapplication/mipmap/no_image").toString());
}
setResult(Activity.RESULT_OK, returnIntent);
finish();
}
});

Activity A(图片和文字可以从B返回给A)

 @Override
public void onActivityResult(int requestCode, int resultCode, Intent data) { // receive from Activity B and populate ListView A
if (resultCode == RESULT_OK) {
if (requestCode == PROJECT_REQUEST_CODE) {
ReceiveType = data.getStringExtra("type");
ReceiveDescription = data.getStringExtra("description");
ReceiveAmount = data.getStringExtra("amount");
imgURI = Uri.parse(data.getStringExtra("img_uri"));
// Toast.makeText(getApplication(),ReceiveType+ReceiveAmount+ReceiveDescription+"",Toast.LENGTH_LONG).show();
if (mClickedPosition == -1) { // if icon clicked
if (obj != null)
obj.addNewItem(ReceiveType, ReceiveAmount, imgURI, ReceiveDescription);
addOrRemoveFooter();

} else {
if (obj != null)
obj.changeItem(mClickedPosition, ReceiveType, ReceiveAmount, imgURI, ReceiveDescription);
}
}
}
}

有趣的部分来了。当 Activity A 中的提交按钮被点击时

 public void uploadImageAndText(ArrayList<ImageAndText> listItems, final String id) {
JSONArray jsonArray = new JSONArray();
try {
for (ImageAndText i : listItems) {
JSONObject object = new JSONObject();
String type = i.getType();
String[] Type = type.split(":");
object.put("type", Type[1]);
// Toast.makeText(getApplicationContext(), Type[1], Toast.LENGTH_LONG).show();
String amount = i.getAmount();
String[] Amount = amount.split(":");
object.put("amount", Amount[1]);
String description = i.getDescription();
String[] Description = description.split(":");
object.put("description", Description[1]);
String image=i.getImage().toString();
Uri imageUri = Uri.parse(image);
object.put("image", image);
object.put("ts_id", id);
object.put(Configs.KEY_IMAGE,getStringImage(imageUri));
jsonArray.put(object);
}
} catch (JSONException e) {
e.printStackTrace();
}

AddStaff ru = new AddStaff(jsonArray);
ru.execute();

}

class AddStaff extends AsyncTask<String, Void, String> {
ProgressDialog loading;

JSONArray jsonArray;

AddStaff(JSONArray jsonArray) {
this.jsonArray = jsonArray;
}

@Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(AddClaims.this, "Please Wait", null, true, true);
}

@Override
protected String doInBackground(String... params) {
try {
HashMap<String, String> data = new HashMap<String, String>();
data.put("listItems", jsonArray.toString());
//Log.d("log", "This json = " + jsonArray.toString());
RequestHandler rh = new RequestHandler();
String result = rh.sendPostRequest(Configs.STAFF_BENEFIT, data);
return result;
} catch (Exception e) {
return "";
}
}

@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
//Toast.makeText(getApplicationContext(), s, Toast.LENGTH_LONG).show();
}
}


public String getStringImage(Uri imgUri) {

try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), imgUri);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
} catch (Exception e) {
}

return "";
}
}

我在这里做了很多测试。如果所选图片来自downloadwhatsapp,则可以插入。如果我从 My photos 中选择图像,则不会插入任何图像。为什么会这样???

SaffBenefit.php

<?php
if( $_SERVER['REQUEST_METHOD']=='POST' ){
if( !empty( $_POST['listItems'] ) ){
$listItems = json_decode( $_POST['listItems'], true );
$mysqli = new mysqli("localhost", "spiral69_wp178", "q1w2e3r4", "spiral69_androiddb");
if( $mysqli->connect_errno ) echo "Failed to connect to MySQL";
$sql="INSERT INTO `staff_benefit`
( `type`, `amount`, `description`, `image`, `ts_id` )
VALUES ( ?, ?, ?, ?, ? )";
if($stmt=$mysqli->prepare($sql )){
$url="http://www.ss.com/Android/CRUD/PhotoUpload/";
foreach( $listItems as $item ){
$id = uniqid();
$image_name = $id.".png";
$save_path = 'PhotoUpload/'.$image_name;
$image_url = $url.$image_name;
$bytes=file_put_contents($save_path, base64_decode($item['image']));
if( !$bytes ){
echo 'Error saving image';
}else{
$stmt->bind_param('sssss',
$item['type'],
$item['amount'],
$item['description'],
$image_url,
$item['ts_id'] );
if( !$res=$stmt->execute()){
echo 'Query failed with code: '.$stmt->errno;
}
}
}
}
$mysqli->close();
}
}
?>

最佳答案

可能存在您发送到服务器的 base64 编码数据 太高而 MySql 无法处理的问题。你应该做的是将压缩值更改为 70% 作为 bitmap.compress(Bitmap.CompressFormat.JPEG, 70, baos);

希望这对您有所帮助。

关于android - 图像未从 android 插入到 MySQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35195006/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com