C# Convert.ToBase64String always rotate my image 90 degrees counter clockwise - c#

I'm working on a function that takes a photo and convert it to base64 string. But for some reason, and i tried looking this up, Convert.ToBase64String always rotate my image 90 degrees counter clockwise. I have tried looking this up but couldnt find anyone with similair issue. Here's the code
private async Task<string> GetPhotoBase64StringAsync(int compressionQuality = 50, PhotoSize photoSize = PhotoSize.Medium)
{
string filename = $"{DateTime.Now.ToString("MMddyyyy_Hmmtt")}.jpg";
var photo = await UtilityService.OpenCameraAsync(filename, compressionQuality, photoSize);
if (photo != null)
{
var bytes = await photo.GetStream().ConvertToBytes();
var base64string = Convert.ToBase64String(bytes);
return base64string
}
return string.Empty;
}
photo is an object that is returned by the xamarin plugin that im using. I know for a fact that the plugin returns the image in the right orientation because i displayed afterward and its not rotated.
The problem happens when i convert the image to stream and from stream to base64. If i put a breakpoint at return base64string and copy and paste the base64 string to an online base64 to image convert, the image would come out rotated 90 degrees counter clockwise.
I have also tried
var base64string = bytes.ToBase64String(); but that didnt work either.
This is so strange and i have never countered this before.

Have you tried the good old IO.MemoryStream instead of .ConvertToBytes()?
byte[] bytes;
using (var memoryStream = new System.IO.MemoryStream())
{
photo.GetStream().CopyTo(memoryStream);
bytes = memoryStream.ToArray();
}

the problem was with the plugin. I'm using MediaPlugin and had to use the other getstream method
var bytes = await photo.GetStreamWithImageRotatedForExternalStorage().ConvertToBytes();
var base64string = Convert.ToBase64String(bytes);
return base64string

Related

MediaPicker.CapturePhotoAsync() Image rotated 90 degree

When I Capture a Photo with the following code , I get the saved photo rotated 90 degree in Android and iOS
is there any solution for this issue? so I get the saved image orientation adjusted properly
FileResult photo = await MediaPicker.CapturePhotoAsync();
using Stream sourceStream = await photo.OpenReadAsync();
var picture = PlatformImage.FromStream(sourceStream);
string localFilePath = $"{FileSystem.CacheDirectory}/{photo.FileName}";
using FileStream localFileStream = File.OpenWrite(localFilePath);
await picture.SaveAsync(localFileStream, ImageFormat.Jpeg, quality: 0.90f);
Save the bytes of the source stream directly to the file stream.
Dont use an intermediate picture.

Rotate byte array Image and encode to Base64 string

I am having a very difficult time trying to figure this one out:
I am working with a front-end which
Reads an image taken from a mobile device to a byte array
Converts the byte array to be stored as a Base64 string
Sends the Base64 string to a database
The back-end is only slated to store images as Base64 strings, as it later embeds the image as a Base64 string to an email for the user whose email application will only show Base64-embedded images. The problem is that the images are embedding 90 degrees counter-clockwise in the email, so I am trying to rotate the image 90 degrees before encoding the base64 string which is inserted into a Sql stored procedure (executed from the application). I feel like this code should simply do the trick:
HttpPostedFile img = imageUpload.PostedFile;
Stream stream = img.InputStream;
BinaryReader binaryReader = new BinaryReader(stream);
byte[] bytes = binaryReader.ReadBytes((int)stream.Length);
// Rotate Image Code (help):
using (var memoryStream = new MemoryStream(bytes))
{
var rotateImage = System.Drawing.Image.FromStream(memoryStream); rotateImage.RotateFlip(RotateFlipType.Rotate90FlipNone);
rotateImage.Save(memoryStream, rotateImage.RawFormat);
bytes = memoryStream.ToArray();
}
// End Rotate Image Code
insert.Parameters.AddWithValue("#Image",Convert.ToBase64String(bytes));
But I am receiving an error when I try and run it:
System.ArgumentNullException: Value cannot be null.
Parameter name: encoder at the line "bytes = memoryStream.ToArray();"
When I try and save it as a jpeg the image gets chopped off at the top, but no other formats work.
I think there is a problem in the line:
rotateImage.Save(memoryStream, rotateImage.RawFormat);
Maybe you should specify the format. Try with:
rotateImage.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Jpeg);
Or even better, you can catch and force convertion only when there is an exception:
try
{
rotateImage.Save(memoryStream, rotateImage.RawFormat);
}
catch (System.ArgumentNullException)
{
rotateImage.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Jpeg);
}
I think the issue is related to this answer

C# , convert gif data to binary array to image

this is related with test instrument but need to more help in C# code.
i did more explain here about my question.
i send command to instrument and i just receive data from instrument.
received data is real format (binary) and i just put in to string variable.
here i captured what's inside in string..
http://i.stack.imgur.com/UcYqV.png
then what i want do is i want this string to convert byte array. because my goal is make png file in my pc. instrument manual said this returned data is gif format but returned real type.'
i believe the problem point is when i convert to byte array,,, there are problem...
does anyone has this kind of experiance,.????
/// below is just send command to instrument that i want " Returns an image of the display in .gif format "
my6705B.WriteString("hcop:sdump:data?", true);
string image_format = my6705B.ReadString();
/// what's inside string image_format ??![i attached screenshot png file. this is what i received from instrument. (manual said this is Returns an image of the display in .gif format)][1] ![png file][2]
http://i.stack.imgur.com/UcYqV.png
/// now here i think i did something wrong,
/// the goal is i want change this return data to gif or png or image file.
/// any solution is ok for me
/// i just try that change this data to byte array and then try to change image file.
/// i think some error here because my code success to convert byte array then create image,,, error
//// i believe that i did something wrong in convert byte array.....
System.Text.UnicodeEncoding encode = new System.Text.UnicodeEncoding();
byte[] byte_array22 = encode.GetBytes(image_format);
MemoryStream ms4 = new MemoryStream(byte_array22);
Image image = Image.FromStream(ms4); //// error point
image.Save(#"C:\Users\Administrator\Desktop\imageTest.png");
i believe that my explain is in comment.
let me explain again that my goal is convert gif data to image file.
instrument give us Returns an image of the display in .gif format.
i received this data to string array. < i dont know this is correct or not but for now i put to string array > then i just want to png or jpg file with this gif data.
please advice,.
Joseph Choi
Please Try ImageFormat Like
image.Save(#"C:\Users\Administrator\Desktop\imageTest.png", System.Drawing.Imaging.ImageFormat.Png);
Update:
byte[] byte_array22 = Encoding.Unicode.GetBytes(image_format);
MemoryStream ms4 = new MemoryStream(byte_array22);
Image image = Image.FromStream(ms4, true, true);
image.Save(#"C:\Users\Administrator\Desktop\imageTest.png",System.Drawing.Imaging.ImageFormat.Png);
Hmm ... here are a couple of methods to transform an image to Base64 format (string), and back.
private string ImageToBase64(Image image, System.Drawing.Imaging.ImageFormat format)
{
using (MemoryStream ms = new MemoryStream())
{
// Convert Image to byte[]
image.Save(ms, format);
byte[] imageBytes = ms.ToArray();
// Convert byte[] to Base64 String
string base64String = Convert.ToBase64String(imageBytes);
return base64String;
}
}
private Image Base64ToImage(string base64String)
{
// Convert Base64 String to byte[]
byte[] imageBytes = Convert.FromBase64String(base64String);
using (var ms = new MemoryStream(imageBytes, 0, imageBytes.Length))
{
// Convert byte[] to Image
ms.Write(imageBytes, 0, imageBytes.Length);
Image image = Image.FromStream(ms, true);
return image;
}
}
You can use them and play with them to see if they suit you.
I'm not sure that taking an image and simply dumping it into string array will help you much.

Getting a Byte Array from the audio file saved by Media.RecordSoundAction

I have a file that is created using
var recordIntent = new Intent(MediaStore.Audio.Media.RecordSoundAction);
I have no problems retrieving the URI of this file. And I can play it back using MediaPlayer without any difficulties.
However, I would like to send this as a response to my webAPI, and am looking at a way to convert the Audio File represented by this URI to a byte array that I can convert to JSON.
With an image file i can do something like
Bitmap bitmap = MediaStore.Images.Media.GetBitmap(ContentResolver, responseUri);
bitmap.Compress(Bitmap.CompressFormat.Png, 0, stream);
byte[] bitmapData = stream.ToArray();
Is there a similar way I can retrieve the Byte Array data from my audio URI?
edit:
formatting of Audio URI.
responseUri = {content://media/external/audio/media/21}
Taken from a ton of different SO answers, and a little bit of extra conversion for mono from Java I came up with these results.
public String GetRealPathFromUri(Uri contentUri){
String[] proj = {MediaStore.Audio.AudioColumns.Data};
ICursor cursor = ManagedQuery(contentUri, proj, null, null, null);
int column_index = cursor.GetColumnIndex(MediaStore.Audio.AudioColumns.Data);
cursor.MoveToFirst();
return cursor.GetString(column_index);
}
var responseRealPath = GetRealPathFromUri(responseUri);
var getBytes = System.IO.File.ReadAllBytes(responseRealPath);
var responseBase = Convert.ToBase64String(getBytes);

Failing to upload Image in base64 bits via XML-RPC [Wordpress/NGG]

I have literally tried every possible way on this but apparently I just can't figure out the right one.
I am trying to upload images to the next-gen gallery that is installed on a wordpress blog. Everything about xml-rpc is working since I am able to do all other stuff with it.
The problem is that server returns an error saying the image is not a valid one. Which is quite obvious that the problem is about base64. However, for test purposes i copied and checked the base64 string and realized it is just right, it converts right to the image using an external base64 to image converter.
This is the line that submits the query.
result = categories.newImage(1, "admin", "password", newImage);
The struct for newImage is;
public struct imageI
{
public string name;
public string type;
public string bits;
public bool overwrite;
public int gallery;
public int image_id;
}
And this is how a new one is initialized, along with converting an image into base64
//Creating the image base64 string
string filename = "asd.jpg";
Image image1 = Image.FromFile(filename);
string base64 = ImageToBase64(image1, image1.RawFormat);
//for test purposes i copied and checked the base64 and it is just right, it converts right to the image using an external base64 to image converter.
Clipboard.SetText(base64);
//Creating a newImage
imageI newImage = default(imageI);
newImage.name = "newImage";
newImage.bits = base64;
newImage.gallery= 86;
And finally my method "ImageToBase64(Image, ImageFomat)";
public string ImageToBase64(Image image, System.Drawing.Imaging.ImageFormat format)
{
using (MemoryStream ms = new MemoryStream())
{
// Convert Image to byte[]
image.Save(ms, format);
byte[] imageBytes = ms.ToArray();
// Convert byte[] to Base64 String
string base64String = Convert.ToBase64String(imageBytes);
return base64String;
}
}
In case anybody bumps on this, I figured it out, on the line;
newImage.name = "newImage"; the file name should be the same with the one you are uploading, or at least it should have the same extension so that the function in xml-rpc file can resolve the extension and check if it's okay to upload or not.

Categories

Resources