简体   繁体   中英

Sending Base64 Image to server and then pulling from the server to display later Xamarin

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.

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

    $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

$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

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

    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!

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 ?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM