Convert base64 string to jpg/file - c#

I am struggling to find a way to convert a base 64 string to a jpeg or a file without using the Image class. Is it possible to create the file and not save it locally and upload to Azure blob storage?
var bytes = Convert.FromBase64String(base64String);

To keep it completely clean and simple, use something like this:
using (var img = new MemoryStream(bytes))
{
cloudBlockBlob.UploadFromStream(img);
}
This creates a MemoryStream that you can use to call CloudBlockBlob.UploadFromStream().
Edit
Or, like #mike-z said in the comment below, you can use CloudBlockBlob.UploadFromByteArray() directly.

Related

Convert Base64 String to an Image File and Save it to File System?

I am trying to make a .Net 6 console application that would take in a base64string and then save it to the file system as an actual image file
Example
I have this image
https://cdn.pixabay.com/photo/2016/03/28/12/35/cat-1285634_960_720.png
I would have this image already as a base64 string.
Now I want to save to my file system as "cat-1285634_960_720.png"
I just can't figure out how to do it. All the examples I see say to use Image.Save() but I can't find that in .Net6 and looks like it is removed.
First convert the base64 string to a byte array and then use File.WriteAllBytes(...) to save it:
byte[] imageByteArray = Convert.FromBase64String(base64String);
File.WriteAllBytes("image.png", imageByteArray);

Saving File from web to Database c#

Im making this website,where the user has a form in which they can choose a file from their computer,and upload it, but i don't know how i can use it. I'm using MVC and a Web Service also in C# where im handling the connection to the Database,where I have to save the file.The file can be a pdf,word or an image.
So the question is,how can I save it and also check its size.Thank you
You can use the ContentLength property of HttpPostedFileBase to get the size of the file -
https://msdn.microsoft.com/en-us/library/system.web.httppostedfilebase.contentlength(v=vs.110).aspx
Then save the InputStream to a byte array
using (MemoryStream stream = new MemoryStream())
{
file.InputStream.CopyTo(stream);
bytes = stream.ToArray();
}
Next assign the byte array to a SqlDbType.VarBinary stored procedure parameter to save it back to the database - assuming this is SQL Server.

System.drawing.Image PathTooLong

I need to handle Images with really long paths (no way to save to shorter paths because files already exist in company). For the System.IO.path I had the same problem and found AlphaFS (can handle long paths way over 260 chars), which works perfectly. Is there any way to do the same thing for the System.drawing.Image class?
Id need that in general, but as an example I get the PathTooLong-Exception when calling Image.FromFile(path);
No, there is not. You could load the file yourself, and then read the image from a stream:
using (MemoryStream ms = new MemoryStream(yourOwnReadBytes))
{
Image i = Image.FromStream(ms);
}

Using C# to convert base30 image from jsignature

I need some help about .net method to convert jsignature exported data.
I have an Android app sending base30 compressed data (for example "quaok1C2S3Q3W3A2A2I1Uk1y800Z6c1y1y1W2G2w2C2u1O1M1wie800Y2ccm1A1C1Q1S1U2G2y2M1O1u1y4424681y1C1Q2M2Q2w2A2woce_dC200Z2688408ccoeiamiga800000Y48gic1u1ucmaes866402000Z224420000000000002")
and a .Net web service (rest) receving data in order to save them to database and do some business.
At the moment I'm experimenting some problem in converting data from base30 to image.
As example, I'm referring to the SignatureDataConversion_dotNet code in the "extras" folder of the jsignature zip (https://github.com/willowsystems/jSignature) in order to do the conversion and manage data.
But something is not working for me...or, maybe, I've not completely understood how to manage base30 signature in .Net
This is a piece of the code I'm using:
Base30Converter conv = new Base30Converter();
int[][][] bytearray = conv.GetData(base30_string_from_app);
string actual = jSignature.Tools.SVGConverter.ToSVG(bytearray);
var byteArray = Encoding.ASCII.GetBytes(actual);
using (var stream = new MemoryStream(byteArray))
{
var svgDocument = SvgDocument.Open(stream);
var bitmap = svgDocument.Draw();
bitmap.Save("D:\prova.png", ImageFormat.Png);
}
But the image I get seems to be a "partion" of the whole signature sent, with only some strokes.
I've also checked the string I am manipulating: it is the same of what the app is sending.
As confirmation of this I succed in importing it on a html canvas, using jSignature "setData" method.
Thanks in advance for any help
As another example of the probable issue with the base30 conversion to svg in .Net, here we have the svg conversion of a signature exportet from http://willowsystems.github.io/jSignature/#/demo/
[svg]
[https://] dl.dropboxusercontent.com/u/77767500/SVG_from_jsignature_site.svg
this is the base 30 conversion of the same sign:
7yf1Ul1H4232121Z4577dabdllhhne1uf6423Y2587ddn1v1x1G1A1D1wpordd8431Z1338ffppkm1v1Db964210Y158b46ffgqkhqfef8673523_3EZ2519332455410Y315329745ba9me5343421200100000Z22345233345323311000Y142853746743121000Z10041112224332_jVZ746ba553200Y12368cabceb8a74200Z234a4ebcebfdbc65Y68afjdjd9f864334_4SZ110000Y3368745322000000Z1123355584323113000000Y31Z101101201001221
Trying to convert it using
Base30Converter conv = new Base30Converter();
int[][][] bytearray = conv.GetData(stream_to_convert);
string actual = jSignature.Tools.SVGConverter.ToSVG(bytearray);
i get:
[https://] dl.dropboxusercontent.com/u/77767500/SVG_from_jsignature_lib.svg
As you can see the two "svg" conversion seems to be different.
So, maybe, there is something not working properly in the jSignature.Tools for .Net ...
It took me a lot of trial and error with the .NET tools included in the jSignature package, but here's how I eventually got it to generate a PNG from a base30 jSignature string. I'm using VB .NET and returning a System.Drawing.Image (which you can output however you want):
Public Function GetSignaturePNG() As System.Drawing.Image
'jSignature conversion from base30 to SVG
Dim base30Converter As New jSignature.Tools.Base30Converter()
Dim arrBase30Data As Integer()()() = base30Converter.GetData(Me.SigBase30) 'our original base30 string
Dim strSVG As String = jSignature.Tools.SVGConverter.ToSVG(arrBase30Data)
'first convert it to SVG
Dim mySVG As SvgDocument
Dim newStream As New System.IO.MemoryStream(System.Text.ASCIIEncoding.[Default].GetBytes(strSVG))
mySVG = SvgDocument.Open(newStream, Nothing)
'then convert it to PNG
Dim tempStream As New System.IO.MemoryStream()
mySVG.Draw().Save(tempStream, System.Drawing.Imaging.ImageFormat.Png)
Dim img As System.Drawing.Image = System.Drawing.Image.FromStream(tempStream)
Return img
End Function
Update 6.20.2014: Leo, I was able to successfully export your base30 signature string (listed in your original question) as both SVG and PNG. And I got the entire "leo" signature, not just the few broken strokes. So I'm not sure what we're doing differently. Are you sure you're passing in the entire base30 string to the function?
The SVGConverter class uses string.Format to output decimals to the string. If your current culture is e.g. set to German, it will output fractions with a comma instead of points. So, add CultureInfo.InvariantCulture as the first argument to each String.Format in that class to make sure the SVG output is formatted with decimal points.

Decompressing a Zip file from a string

I'm fetching an object from couchbase where one of the fields has a file. The file is zipped and then encoded in base64.
How would I be able to take this string and decompress it back to the original file?
Then, if I'm using ASP.MVC 4 - How would I send it back to the browser as a downloadable file?
The original file is being created on a Linux system and decoded on a Windows system (C#).
You should use Convert.FromBase64String to get the bytes, then decompress, and then use Controller.File to have the client download the file. To decompress, you need to open the zip file using some sort of ZIP library. .NET 4.5's built-in ZipArchive class should work. Or you could use another library, both SharpZipLib and DotNetZip support reading from streams.
public ActionResult MyAction()
{
string base64String = // get from Linux system
byte[] zipBytes = Convert.FromBase64String(base64String);
using (var zipStream = new MemoryStream(zipBytes))
using (var zipArchive = new ZipArchive(zipStream))
{
var entry = zipArchive.Entries.Single();
string mimeType = MimeMapping.GetMimeMapping(entry.Name);
using (var decompressedStream = entry.Open())
return File(decompressedStream, mimeType);
}
}
You'll also need the MIME type of the file, you can use MimeMapping.GetMimeMapping to help you get that for most common types.
I've used SharpZipLib successfully for this type of task in the past.
For an example that's very close to what you need to do have a look here.
Basically, the steps should be something like this:
you get the compressed input as a string from the database
create a MemoryStream and write the string to it
seek back to the beginning of the memory stream
use the MemoryStream as an input to the SharpZipLib ZipFile class
follow the example provided above to unpack the contents of the ZipFile
Update
If the string contains only the zipped contents of the file (not a full Zip archive) then you can simply use the GZipStream class in .NET to unzip the contents. You can find a sample here. But the initial steps are the same as above (get string from db, write to memory stream, feed memory stream as input to the GZipStream to decompress).

Categories