Svg to base64 without third party libraries c# - c#

I am trying to convert svg image URL to base 64, the problem is that i am limited and I can't use third party libraries in this project.
Is there any possible way to do that?
I've tried this but it did not work. Someone said that svg is a file not an image so DownloadData won't work right.
byte[] imageBytes;
string base64String = string.Empty;
using (WebClient wc = new WebClient())
{
imageBytes = wc.DownloadData(appSuggestion?.IconUri.AbsoluteUri);
base64String = Convert.ToBase64String(imageBytes);
}
Any Idea what can I do?
Edit:
I wanted to use it in a data url "data:image/svg+xml;base64,[base64String]" in adaptive cards as an image url, at first I thought that adaptive cards are not supporting svg, but then I tried to write the url on chrome and it also didn't show the image.

Using DownloadData is perfectly valid here as it will return the content of the URI returned by the server as byte[]. The base64 conversion is also correct. What you've got so far will give you the base64-encoded content of any URI. I've just tested this and it works correctly.
Here's my test code to produce a data: URI from an SVG file hosted on a remote web server:
public string SVGUriToDataUri(Uri src)
{
using (var wc = new System.Net.WebClient())
{
var imageBytes = wc.DownloadData(src);
var imageBase64 = Convert.ToBase64String(imageBytes);
return "data:image/svg+xml;base64," + {imageBase64};
}
}
Putting the output of that into the address bar in Chrome displays the image as expected.
Here's a more general version that gets the mime type from the server:
public string DownloadAsDataUri(Uri src)
{
using (var wc = new System.Net.WebClient())
{
var imageBytes = wc.DownloadData(src);
var imageBase64 = Convert.ToBase64String(imageBytes);
var mimeType = wc.ResponseHeaders["content-type"];
if (mimeType.Contains(';'))
mimeType = mimeType.Split(';')[0];
return $"data:{mimeType};base64,{imageBase64}";
}
}
If it's a PNG, BMP, ICO or whatever and it works when you put the URI itself then this should work. It works for me with the image link you posted - which is SVG.
If this does not work for then please post a copy of the output so we can investigate. At this point the only other option I can think of is that appSuggestion?.IconUri.AbsoluteUri is not giving you the correct address.

Related

How use the Byte Array of a image?

So, i am getting the byte array of a LongRaw image from Oracle...
I am using a webapi to this. After get the array, how i use it on the Client-side ?
Do Its better i convert to base64string and pass this value converting just at the client side ?
cmd.InitialLONGFetchSize = -1;
var reader = cmd.ExecuteReader();
if (reader.Read())
{
// Fetch the LONG RAW
OracleBinary imgBinary = reader.GetOracleBinary(0);
// Get the bytes from the binary obj
byte[] imgBytes = imgBinary.IsNull ? null : imgBinary.Value;
//var imgString = Uri.EscapeDataString(Convert.ToBase64String(imgBytes));
}
//CRIO A LISTA
lretorno.Load(reader, LoadOption.OverwriteChanges, "BUSCAFOTO");
reader.Close();
connection.Close();
connection.Dispose();
var teste = lretorno.Tables[0].AsEnumerable().Select(row => new FotoEnvolvido
{
FOTO = (byte[])(row["FOTO"]),
//FOTO = Convert.ToString(row["FOTO"]),
});
return teste;
You can write a Web API Controller that returns the binary data of an image. Base64 strings impose a overhead of the amount of bytes that have to be transmitted. Please avoid this.
A sample controller can look like this example:
public class WebApiController : ApiController
{
public async Task<HttpResponseMessage> Get(string id)
{
var bytes = await GetBytesFromDataLayerAsync(id);
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
var stream = new MemoryStream(bytes);
result.Content = new StreamContent(stream);
result.Content.Headers.ContentType =
new MediaTypeHeaderValue("image/jpeg");
return result;
}
private async Task<byte[]> GetBytesFromDataLayerAsync(string id)
{
// put your Oracle logic here
return ...
}
}
Depending on what your doing as rboe said writing the bytes directly to the client will save some data size(approx. 37%) and computing overhead. If your not only displaying jpeg images you should also set the mime-type to the correct value... take a look at this source for a rather complete set of extension to mime-type mappings. If you do not know the mime-type you can try "application/octet-stream" as that is the general mime-type for binary data.
If your displaying your content via web browser you could just use an <img> tag something like <img src="view_image.aspx?id=5"> you can even create the dynamically with javascript/jQuery.
If you really do want the image data embedded in a json request which might be useful if you have a lot of little icons and don't want a ton of requests (with http/2 I don't think this will matter) or another reason, then yes first encode the binary data using...
string base64EncodedData = Convert.ToBase64String(bytes);
If the client is javascript you can decode using the latest browsers native functions
var decodedImageData = window.atob(base64EncodedData);
See:
mozilla.org docs
This answer
This answer
If you are however just sending it to another c# endpoint you can use...
byte[] decodedImageData = Convert.FromBase64String(base64EncodedData);
And like I mentioned in the comment to ensure it's encrypted just make the site only support https:// and if you don't have a SSL cert you can get one for free from http://startssl.com

How to Download image in c# using webclient and use Javascript to get image from aspx page

I've seen fragments of various answers to this questions here and there, and I can't get any of them to work.
The purpose of the code is so I can download an image from the internet via an aspx page. so from Javascript, I'll call the aspx page, which should serve up the data, which I then feed into an Image element, but so far no dice.
I'm currenty trying:
in GetHotlink.aspx page:
System.Net.WebClient wc = new System.Net.WebClient();
byte[] data = wc.DownloadData("http://www.html5canvastutorials.com/demos/assets/darth-vader.jpg");
Context.Response.Clear();
Context.Response.ContentType = "image/JPEG";
Context.Response.OutputStream.Write(data, 0, data.Length);
Context.Response.Flush();
Context.Response.Close();
Context.Response.End();
and in Javascript:
var url = "GetHotlink.aspx";
var tmptxt = call_genpic(url); // call server with filename and minimum layer value.
var imageObj = new Image();
imageObj.setAttribute('src', 'data:image/jpeg;base64,' + tmptxt);
document.body.appendChild(imageObj);
function call_genpic(url) {
var reqObj = createRequest();
reqObj.onreadystatechange = function () {
if (reqObj.readyState == 4) {
//callback
}
}
reqObj.open("GET", url, false);
reqObj.send(null);
var V = "";
V = reqObj.responseText;
return V;
return(reqObj.responseText);
}
I can see that I'm getting a nice chunk of data back from the server when I call the aspx page, but the image that I add to the DOM comes up as the broken image icon. No Darth Vader! I suspect that somewhere along the way Darth is getting into the wrong format, or is getting the wrong header or so. Any ideas?
You are using base64 data as your image source but you are not encoding your response as base64 string. Use this method to convert the byte array to string and serve it back to the client as string not as binary data.
Also your JavaScript code looks all messed up. Why do you have two returns one after another. You should create the image and set its data in the callback (right where you have a comment)

Conversion og BMP instance to png

I have function name uploadLayerIcons which is as follows:
private void uploadLayerIcon(string LayerName)
{
Bitmap icon= new Bitmap(#"C:\Users\HP\Desktop\911\Prism\Prism_Resources\m.png");
System.IO.MemoryStream stream = new System.IO.MemoryStream();
icon.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp);
byte[] imageBytes = stream.ToArray();
// Convert byte[] to Base64 String
string base64String = Convert.ToBase64String(imageBytes);
HttpWebRequest m_ObjRequest; //Request which needed to be sent to server
HttpWebResponse m_ObjResponse; // Response which is sent back from the server to the client
StreamReader reader = null; // making a stream reader to read the web pageand initialize it to null
string m_Url = "http://192.168.1.30/muneem/erp/uploadIcon.php" + "?bitmap=" + base64String + "&layerName=" + LayerName; // the url of that web page
string m_Response = "";
m_ObjRequest = (HttpWebRequest)WebRequest.Create(m_Url); // creating the url and setting the values
m_ObjRequest.Method = "GET";
m_ObjRequest.ContentType = "application/json; charset=utf-8";
//m_ObjRequest.ContentLength = 500;
m_ObjRequest.KeepAlive = false;
m_ObjResponse = (HttpWebResponse)m_ObjRequest.GetResponse(); // getting response from the server
using (reader = new StreamReader(m_ObjResponse.GetResponseStream())) // using stream reader to read the web page
{
m_Response = reader.ReadToEnd();
reader.Close(); // Close the StreamReader
}
m_ObjResponse.Close();
m_ObjRequest = null;
m_ObjResponse = null;
}
UploadIcon.php file is as follows:
<?php
$bitmap=$_GET['bitmap'];
$name=$_GET['layerName'];
$data = base64_decode($bitmap);
$filepath="app/uams/uploadedImages/".$name.".jpg";
file_put_contents($filepath,$data);
?>
Its not converting correctly the same image which i have sent to server.
I have search on internet many thing but all in vain. I have also tried this thing
Bitmap icon= new Bitmap(#"C:\Users\HP\Desktop\911\Prism\Prism_Resources\m.png");
icon.save("Path of srrver")
But its not working.
So, you are doing it pretty much wrong. First of all, if you change the extension of the file to .jpg it does not automagically become jpg image.
So, what I suggest you to do is to send the raw png data instead of bitmap, and then using something like this in php:
<?
$imagedata = $_POST["data"];
$im = imagecreatefromstring($imagedata);
$filepath="app/uams/uploadedImages/image.jpg";
imagejpeg($im,$filepath);
?>
Also, as pointed out in previous answer by #DoXicK, do not send file by GET method, you should post it instead, and that is what this example is based on.
PHP's function imagecreatefromstring identifies the image type, and creates the gdlib object accordingly (but it does not work very well with bitmaps). That is why I suggested that you use raw png data instead of converting it to bitmap. Also, bitmap data is unneccesary large for transfer.
For imagecreatefromstring to work you need GD Library installed and enabled. To see if it is enabled create an empty file (named for example info.php) and inside it put only
<?
phpinfo();
?>
If you see GD Support set to Enable on the page, when you open the file, you have gdlib enabled. If you do not see it, do the following:
On windows find ;extension=php_gd2.dll in php.ini file of your php installation, and uncomment it (remove ; from the beginning) so it now is extension=php_gd2.dll and then restart Apache.
On linux you need to do sudo apt-get install php5-gd and then restart Apache.
you are loading a PNG to BMP file format
You are sending a file by GET
you are saving the BMP file as JPG te minute you receive the BMP
So:
Don't open as PNG as BMP. open a PNG as PNG as it is either smaller or the same size. There is no need for the BMP here...
POST it
Just because you call it a JPG, doesn't make it a JPG. It currently is a BMP, saved to a JPG.
IF it even saves a .jpg file, it is a .bmp file with the wrong extension.

Load image from url save it as byte

I getting one image with HTMLAgilityPack and then I want to load it as byte so I could save it in database.
byte[] bIMG = File.ReadAllBytes(doc.DocumentNode.SelectSingleNode("//img[#class='image']").Attributes["src"].Value);
But it says URI formats are not supported. how else I can do that?
EDIT: doc.DocumentNode.SelectSingleNode("//img[#class='image']").Attributes["src"].Value gives a link
The System.IO.File class can't read web URIs - you can use the WebClient for this:
byte[] imageAsByteArray;
using(var webClient = new WebClient())
{
imageAsByteArray = webClient.DownloadData("uri src");
}

Disallowed key characters while uploading image in base64 format

I'm developing Windows phone(8.0)apps and I'm new to it,I'm using below code to post image to server in Base64 format using post client
Uri uri = new Uri(UPLOAD_IMAGE_PATH);
UploadImageData requestData = new UploadImageData();
requestData.image = base64String;
string jsonString = JsonConvert.SerializeObject(requestData);
PostClient proxy = new PostClient(jsonString);
proxy.DownloadStringCompleted += new PostClient.DownloadStringCompletedHandler(proxy_DownloadStringCompleted);
proxy.DownloadStringAsync(uri);
where base64String is my image string encoded in Bae64 by using below code
internal static string ImageToBase64String(Stream choosenPhoto,Image image)
{
WriteableBitmap bmp = new WriteableBitmap((BitmapSource)image.Source);
byte[] byteArray;
using (MemoryStream stream = new MemoryStream())
{
bmp.SaveJpeg(stream, bmp.PixelWidth, bmp.PixelHeight, 0, 100);
byteArray = stream.ToArray();
return Convert.ToBase64String(byteArray);
}
}
In below response it returns "disallowed key charaters" on result.
void proxy_DownloadStringCompleted(object sender, WindowsPhonePostClient.DownloadStringCompletedEventArgs e)
{
string result = e.Result;
}
But when i post same JSON string using REST Client from Mozilla, JSON response from server is successfull.
I searched about this and i got some links link 1, link 2 that i need to allow characters on server side in Input.php file, So exactly what kind of character i need to allow. It works from REST Client did i miss something in my C# code, Please help me
It doesn't seem to explicitly mention the Base64 string (unless I'm missing something, having never developed for a WinPhone OS). Have you checked the URL that you're sending a POST request to?

Categories