Loading base64 string image to DocuVieware - c#

Image files are saved in base64 string format in the database.
I'm trying to load the image using DocuVieware via MemoryStream but failed.
Does anyone tried this kind of approach?
if (this.IsPostBack != true)
{
var file = new DataFileManager().GetImageByID(userID);
byte[] byt = System.Text.Encoding.UTF8.GetBytes(file.CurrentImage);
DocuVieware1.LoadFromStream(new MemoryStream(byt, 0, byt.Length), true);
}

You probably need to replace:
byte[] byt = System.Text.Encoding.UTF8.GetBytes(file.CurrentImage);
by:
byte[] data = Convert.FromBase64String(file.CurrentImage);
Ref: https://learn.microsoft.com/en-us/dotnet/api/system.convert.frombase64string?view=netframework-4.8

Related

Convert.FromBase64String usage in VS22 causing output dll to be quarantined by CrowdStrike

I have a C# project that uses Convert.FromBase64String(string) that builds properly in VS2019 but in VS22, the output dll gets immediately quarantined by CrowdStrike. I can't explain why CrowdStrike only finds potential security issues with VS22 and not VS2019.
Is there a way to create an image from Base64 without the use of FromBase64String?
I've found leaving the data:image/png;base64 header in the string allows the project to build and output the dll but Convert.FromBase64String(string) fails with 'The input is not a valid Base-64 string as it contains a non-base 64 character...'
In trying to find a workaround for FromBase64String(), I tried converting the Base64 string to a Byte[] with GetBytes(), formatting for proper length, converting to char[], then ToBase64CharArray, and finally back to my imageBytes with Convert.FromBase64CharArray. This builds and creates my dll but fails with 'invalid parameter' in Image.FromStream(memoryStream)
public static Image Base64ToImage(string base64String)
{
// Remove the data:image/png;base64
base64String = base64String.Substring(base64String.IndexOf(',') + 1);
base64String = base64String.Trim('\0');
// Convert Base64 String to byte[]
byte[] imageBytes = Convert.FromBase64String(base64String);
using (MemoryStream memoryStream = new MemoryStream(imageBytes, 0, imageBytes.Length))
{
// Convert byte[] to Image
if (imageBytes.Length > 0)
{
using (var image = ((Bitmap)Image.FromStream(memoryStream)).RemoveAlpha())
{
return new Bitmap(image);
}
}
else
return null;
}
}

How to convert a base64 source to image source in xamarin

I want to convert a svg base64 string to image and need to assign that to image source in Xamarin How to implement the same . Please help on this.
Var dImage="data:image/avg+XML;base64,PD94b.....=="
My base64 string is in the above format.I did the normal base64 to image convertion but it didn't worked.
Can you please try it with plain data (without mime-type,...):
=> Convert.FromBase64String("PD94b.....==");
var dImage = "data:image/avg+XML;base64,PD94b.....==";
var base64 = dImage.Split(',')[1];
byte[] bytes = Convert.FromBase64String(base64);
Image image;
using (MemoryStream ms = new MemoryStream(bytes))
{
image = Image.FromStream(ms);
}

How do I write a byteArray to a specific path

I currently have a method which is taking a picture and saving it..
Once saved I call this method to encrypt the file from a string path
but im not sure how to save it.. I wanted to do
string path = #"C:/somePath"
File.WriteAllBytes(path);
but that doesnt work obv. So how do I properly save a bytearray?
string key = GetUniqueKey(32);
byte[] encKey = Encoding.UTF8.GetBytes(key);
byte[] imgBytes = File.ReadAllBytes(path);
byte[] ebytes = encrypt.AESEncrypt(imgBytes, encKey);
File.WriteAllBytes();
If you actually check the parameters it's asking for, you need to provide the bytes as well as the path.
So:
string path = #"C:/somePath/somefile.png"
string key = GetUniqueKey(32);
byte[] encKey = Encoding.UTF8.GetBytes(key);
byte[] imgBytes = File.ReadAllBytes(path);
byte[] ebytes = encrypt.AESEncrypt(imgBytes, encKey);
File.WriteAllBytes(path, ebytes);
Method's signature is:
File.WriteAllBytes(string path, byte[] bytes)

How to get the ZIP file from Base64 string in Javascript?

I am trying to get the compressed ZIP file back in Javascript. I am able to convert the zip file into Base64 String format. (Zip file is in Server)
Here is my try (at Server Side)
System.IO.FileStream fs = new System.IO.FileStream(SourceFilePath + "Arc.zip", System.IO.FileMode.Open);
Byte[] zipAsBytes = new Byte[fs.Length];
fs.Read(zipAsBytes, 0, zipAsBytes.Length);
String base64String = System.Convert.ToBase64String(zipAsBytes, 0, zipAsBytes.Length);
fs.Close();
if (zipAsBytes.Length > 0)
{
_response.Status = "ZipFile";
_response.Result = base64String;
}
return _json.Serialize(_response);
This part of code returns the JSON data. This JSON data includes the Base64 string. Now what i want to do is to get the original zip file from Base64 string. I searched over the internet but not get the idea.
Is this achievable ?.
It is achievable. First you must convert the Base64 string to an Arraybuffer. Can be done with this function:
function base64ToBuffer(str){
str = window.atob(str); // creates a ASCII string
var buffer = new ArrayBuffer(str.length),
view = new Uint8Array(buffer);
for(var i = 0; i < str.length; i++){
view[i] = str.charCodeAt(i);
}
return buffer;
}
Then, using a library like JSZip, you can convert the ArrayBuffer to a Zip file and read its contents:
var buffer = base64ToBuffer(str);
var zip = new JSZip(buffer);
var fileContent = zip.file("someFileInZip.txt").asText();
JavaScript does not have that functionality.
Theoretically there can be some js library that does this, but it's size probably would be bigger than the original text file itself.
You can also enable gzip compression on your server, so that any output text gets compressed. Most of the browsers would then uncompress the data upon its arrival.

C# - High Quality Byte Array Conversion of Images

I am converting images to byte array and storing in a text file using the following code. I am retrieving them successfully as well.
My concern is that the quality of the retrieved image is not up to the expectation. Is there a way to have better conversion to byte array and retrieving? I am not worried about the space conception.
Please share your thoughts.
string plaintextStoringLocation = #"D:\ImageSource\Cha5.txt";
string bmpSourceLocation = #"D:\ImageSource\Cha50.bmp";
////Read image
Image sourceImg = Image.FromFile(bmpSourceLocation);
////Convert to Byte[]
byte[] clearByteArray = ImageToByteArray(sourceImg);
////Store it for future use (in plain text form)
StoreToLocation(clearByteArray, plaintextStoringLocation);
//Read from binary
byte[] retirevedImageBytes = ReadByteArrayFromFile(plaintextStoringLocation);
//Retrieve from Byte[]
Image destinationImg = ByteArrayToImage(retirevedImageBytes);
//Display Image
pictureBox1.Image = destinationImg;
EDIT: And the solution is - use Base64
//Plain Text Storing Location
string plaintextStoringLocation = #"D:\ImageSource\GirlInflower23.txt";
string bmpSourceLocation = #"D:\ImageSource\GirlInflower1.bmp";
////Read image
Image sourceImg = Image.FromFile(bmpSourceLocation);
string base64StringOfIMage = ImageToBase64(sourceImg, ImageFormat.Bmp);
byte[] byteOfString = Convert.FromBase64String(base64StringOfIMage);
StoreToLocation(byteOfString, plaintextStoringLocation);
byte[] retrievedBytesForStrimngForImage = ReadByteArrayFromFile(plaintextStoringLocation);
MemoryStream memStream = new MemoryStream(retrievedBytesForStrimngForImage);
//memStream.Read();
Image retrievedImg = Image.FromStream(memStream);
pictureBox1.Image = retrievedImg;
Yes, it is possible to get completely lossless storage. If you just store it in its original BMP format there will be no problem. I assume you are converting it to text because you want to send it via some protocol where binary characters will be corrupted.
Instead of whatever you are doing, you could consider using Convert.ToBase64String.
I haven't had any problems with this fragment...try it...if you get good results then the problem is in your Image -> byte[] or byte[] -> Image code :)
Image srcImage;
Image destImage;
// load an image
srcImage = Image.FromFile(filename);
// save the image via stream -> byte[]
using(MemoryStream stream = new MemoryStream()){
image.Save(stream, ImageFormat.xxx);
byte[] saveArray = stream.ToArray();
/*..... strore saveArray......*/
}
// rehydrate
byte[] loadArray = /*...get byte array from storage...*/
using(MemoryStream stream = new MemeoryStream(loadArray)){
destImage = Image.FromStream(stream);
}
pictureBox.Image = dstImage;
// don't forget...dispose of any Image/Stream objects

Categories