Quantcast
Channel: Recent Threads — Xamarin Community Forums
Viewing all articles
Browse latest Browse all 204402

how to upload image to Google Drive with outputstream writer?

$
0
0

Hello, I"m trying the below code, to upload image the google drive, but got no luck. Can someone please guide me in the right direction?

/// Loads a Bitmap from a byte array

public static Bitmap bytesToBitmap(byte[] imageBytes)
{
    Bitmap bitmap = BitmapFactory.DecodeByteArray(imageBytes, 0, imageBytes.Length);
    return bitmap;
}
public void WriteImageToDrive(string filePath, string fileName)
{
    try
    {
        var contentResults = await DriveClass.DriveApi
            .NewDriveContentsAsync(googleDriveClient);

        var writer = new OutputStreamWriter(contentResults.DriveContents.OutputStream);

        Java.IO.File f = new Java.IO.File(filePath);
        FileInputStream fileInputStream = new FileInputStream(f);
        byte fileContent[] = new byte[(int)fileInputStream.Length];
        fileInputStream.read(fileContent);

        Bitmap image = bytesToBitmap(fileContent);
        //Write the bitmap data from it.
        var ms = new MemoryStream();
        image.Compress(Bitmap.CompressFormat.Png, 100, ms);

        ByteArrayOutputStream bitmapStream = new ByteArrayOutputStream();
        int bytesread = 0;
        byte[] buffer = new byte[1024];
        while ((bytesread = ms.Read(buffer, 0, buffer.Length)) > 0)
        {
            var binaryData = buffer.ToArray();
            long arrayLength = (long)((4.0d / 3.0d) * binaryData.Length);
            if (arrayLength % 4 != 0)
            {
                arrayLength += 4 - arrayLength % 4;
            }
            char[] base64CharArray = new char[arrayLength];
            System.Convert.ToBase64CharArray(binaryData,
                                     0,
                                     binaryData.Length,
                                     base64CharArray,
                                     0);

            writer.Write(base64CharArray, 0, base64CharArray.Length);
        }   

        writer.Close();
        MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
                   .SetTitle(fileName)
                   .SetMimeType(mimeType)
                   .Build();
        .....
        .....
    }
    catch (System.Exception ex)
    {
        throw;
    }
}

I have tried different methods to convert stream in to Char[] array, like

  • System.Text.Encoding.UTF8.GetString(fileContent).ToCharArray();
  • Base64Char Array.

Bytes are uploaded as jpg file to google drive, but the jpg file is corrupt and cannot open.

Thanks
Irfan


Viewing all articles
Browse latest Browse all 204402

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>