将Base64图像发送到服务器,然后从服务器拉出以显示以后的Xamarin

时间:2022-12-02 21:38:12

I am new to Xamarin Andriod Development. I am trying to send a Base64 encoded image to mySQL server database and then retrieving the Base64 encoded image in the database when starting the app and displaying it. I have been able to get all the other information in the database to display, the only thing missing is the images when I open the app.

我是Xamarin Andriod Development的新手。我正在尝试将Base64编码的图像发送到mySQL服务器数据库,然后在启动应用程序并显示它时检索数据库中的Base64编码图像。我已经能够显示数据库中的所有其他信息,唯一缺少的是打开应用程序时的图像。

My code looks like this:

我的代码如下所示:

Sending the Image to the server

将图像发送到服务器

    protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
    {
        base.OnActivityResult(requestCode, resultCode, data);

        if (resultCode == Result.Ok)
        {
            int contactID = mContacts[(int)mSelectedPic.Tag].ID;

            Stream stream = ContentResolver.OpenInputStream(data.Data);
            mSelectedPic.SetImageBitmap(DecodeBitmapFromStream(data.Data, 150, 150));

            Bitmap bitmap = BitmapFactory.DecodeStream (stream);
            MemoryStream memStream = new MemoryStream ();
            bitmap.Compress (Bitmap.CompressFormat.Webp, 100, memStream);
            byte[] picData = memStream.ToArray ();

            WebClient client = new WebClient ();
            Uri uri = new Uri ("MYWESBITE/UpdateContact.php");
            NameValueCollection parameters = new NameValueCollection ();
            parameters.Add ("Image", Convert.ToBase64String(picData));
            parameters.Add ("ContactID", contactID.ToString());

            client.UploadValuesAsync (uri, parameters);
            client.UploadValuesCompleted += Client_UploadValuesCompleted;
        }

    }

PHP code to handle the image and store it into the database as a VARBINARY

用于处理映像并将其作为VARBINARY存储到数据库中的PHP代码

    $imgData = base64_encode($mImage);

    $sql = "UPDATE Contact SET ImageBase64 = '$imgData' WHERE ID = '$mContactID'";

    $result = mysql_query($sql, $link);

    if (!$result) {
        echo "DB Error, could not query the database\n";
        echo 'MySQL Error: ' . mysql_error();
        exit;
    }

Then when the app opens it calls this PHP function

然后当应用程序打开时,它会调用此PHP函数

$sql = "SELECT * FROM Contact";

$result = mysql_query($sql, $link);

if (!$result) {
    echo "DB Error, could not query the database\n";
    echo 'MySQL Error: ' . mysql_error();
    exit;
}

//create an array
$contact_array = array();
while($row =mysql_fetch_assoc($result))
{
$contact_array[] = array("ID" => $row["ID"],
                "Name" => $row["Name"],
                "Number" => $row["Number"],
                "ImageBase64" => base64_encode($row["ImageBase64"])
                );
}

echo json_encode($contact_array);

This shows how I turn the base64_encoded string to a byte array

这显示了我如何将base64_encoded字符串转换为字节数组

class Contact
{
    public int ID { get; set; }
    public string Name { get; set; }
    public string Number { get; set; }
    public string ImageBase64 { private get; set; }
    public byte [] Image
    {
        get
        {
            if (ImageBase64 != "" && ImageBase64 != null)
            {
                byte[] image = Convert.FromBase64String (ImageBase64);

                return image;

            }

            return null;

        }
    }
}

MainActivity.cs

MainActivity.cs

    protected override void OnCreate(Bundle bundle)
    {

        base.OnCreate(bundle);
        SetContentView(Resource.Layout.Main);

        mListView = FindViewById<ListView>(Resource.Id.listView);
        mProgressBar = FindViewById<ProgressBar> (Resource.Id.progressBar);

        mClient = new WebClient ();
        mUrl = new Uri ("MYWEBSITE/GetContacts.php");

        //Call the Client
        mClient.DownloadDataAsync (mUrl);
        mClient.DownloadDataCompleted += MClient_DownloadDataCompleted;



    } 

Then finally gets converted to image like this

然后最终转换为这样的图像

    ImageView pic = row.FindViewById<ImageView>(Resource.Id.imgPic);

    if (mContacts[position].Image != null)
    {

        pic.SetImageBitmap(BitmapFactory.DecodeByteArray(mContacts[position].Image, 0, mContacts[position].Image.Length));
    }

Thank you for your time everyone, I hope you can help me figure this out!

感谢大家的时间,我希望你能帮我解决这个问题!

2 个解决方案

#1


0  

A few questions might help to answer this: At what point does it not work? Are you getting an error? or does the image not display?

一些问题可能有助于回答这个问题:它在什么时候不起作用?你收到错误了吗?或图像不显示?

Right off the bat, however, it looks like you are trying to interact from the UI from a background thread. Can you try wrapping the code in your MCClient_Downloaded method in RunOnUIThread?

然而,刚刚开始,看起来你正试图从后台线程的UI进行交互。您可以尝试在RunOnUIThread中的MCClient_Downloaded方法中包装代码吗?

#2


0  

I got it to work now. I changed my database type to be a Medium BLOB instead of a VARBINARY, and then got rid of the base64_encode() on the way into the database and then got rid of the base64_encode() on the way out of the database in the JSON creation.

我现在就开始工作了。我将我的数据库类型更改为中等BLOB而不是VARBINARY,然后在进入数据库的路上删除了base64_encode(),然后在JSON创建中从数据库出来的路上删除了base64_encode() 。

#1


0  

A few questions might help to answer this: At what point does it not work? Are you getting an error? or does the image not display?

一些问题可能有助于回答这个问题:它在什么时候不起作用?你收到错误了吗?或图像不显示?

Right off the bat, however, it looks like you are trying to interact from the UI from a background thread. Can you try wrapping the code in your MCClient_Downloaded method in RunOnUIThread?

然而,刚刚开始,看起来你正试图从后台线程的UI进行交互。您可以尝试在RunOnUIThread中的MCClient_Downloaded方法中包装代码吗?

#2


0  

I got it to work now. I changed my database type to be a Medium BLOB instead of a VARBINARY, and then got rid of the base64_encode() on the way into the database and then got rid of the base64_encode() on the way out of the database in the JSON creation.

我现在就开始工作了。我将我的数据库类型更改为中等BLOB而不是VARBINARY,然后在进入数据库的路上删除了base64_encode(),然后在JSON创建中从数据库出来的路上删除了base64_encode() 。