Load image from url save it as byte - c#

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");
}

Related

Svg to base64 without third party libraries 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.

c# Load Image from ftp server directly into picture box without downloading

I have looked every where for my answer but couldn't find the right solution.Tried many solutions provided but still can't get it through.I uploaded an image in ftp server and i want it to get displayed into picture box in windows form without downloading it into local machine. Is it possible?
Please include complete code for the solution......
Here is a complete code: If any body needs.Make sure the image isn't large!!
public byte [] GetImgByte (string ftpFilePath)
{
WebClient ftpClient = new WebClient();
ftpClient.Credentials = new NetworkCredential(ftpUsername,ftpPassword);
byte[] imageByte = ftpClient.DownloadData(ftpFilePath);
return imageByte;
}
public static Bitmap ByteToImage(byte[] blob)
{
MemoryStream mStream = new MemoryStream();
byte[] pData = blob;
mStream.Write(pData, 0, Convert.ToInt32(pData.Length));
Bitmap bm = new Bitmap(mStream, false);
mStream.Dispose();
return bm;
}
You can use DownloadData to get a byte array and load that into the picturebox - see Download file directly to memory and How to put image in a picture box from a byte[] in C#

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.

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?

Using HttpWebRequest with dynamic URI causes "parameter is not valid" in Image.FromStream

I'm trying to obtain an image to encode to a WordML document. The original version of this function used files, but I needed to change it to get images created on the fly with an aspx page. I've adapted the code to use HttpWebRequest instead of a WebClient. The problem is that I don't think the page request is getting resolved and so the image stream is invalid, generating the error "parameter is not valid" when I invoke Image.FromStream.
public string RenderCitationTableImage(string citation_table_id)
{
string image_content = "";
string _strBaseURL = String.Format("http://{0}",
HttpContext.Current.Request.Url.GetComponents(UriComponents.HostAndPort, UriFormat.Unescaped));
string _strPageURL = String.Format("{0}{1}", _strBaseURL,
ResolveUrl("~/Publication/render_citation_chart.aspx"));
string _staticURL = String.Format("{0}{1}", _strBaseURL,
ResolveUrl("~/Images/table.gif"));
string _fullURL = String.Format("{0}?publication_id={1}&citation_table_layout_id={2}",
_strPageURL, publication_id, citation_table_id);
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(_fullURL);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream image_stream = response.GetResponseStream();
// Read the image data
MemoryStream ms = new MemoryStream();
int num_read;
byte[] crlf = System.Text.Encoding.Default.GetBytes("\r\n");
byte[] buffer = new byte[1024];
for (num_read = image_stream.Read(buffer, 0, 1024); num_read > 0; num_read = image_stream.Read(buffer, 0, 1024))
{
ms.Write(buffer, 0, num_read);
}
// Base 64 Encode the image data
byte[] image_bytes = ms.ToArray();
string encodedImage = Convert.ToBase64String(image_bytes);
ms.Position = 0;
System.Drawing.Image image_original = System.Drawing.Image.FromStream(ms); // <---error here: parameter is not valid
image_stream.Close();
image_content = string.Format("<w:p>{4}<w:r><w:pict><w:binData w:name=\"wordml://{0}\">{1}</w:binData>" +
"<v:shape style=\"width:{2}px;height:{3}px\">" +
"<v:imagedata src=\"wordml://{0}\"/>" +
"</v:shape>" +
"</w:pict></w:r></w:p>", _word_image_id, encodedImage, 800, 400, alignment.center);
image_content = "<w:br w:type=\"text-wrapping\"/>" + image_content + "<w:br w:type=\"text-wrapping\"/>";
}
catch (Exception ex)
{
return ex.ToString();
}
return image_content;
Using a static URI it works fine. If I replace "staticURL" with "fullURL" in the WebRequest.Create method I get the error. Any ideas as to why the page request doesn't fully resolve?
And yes, the full URL resolves fine and shows an image if I post it in the address bar.
UPDATE:
Just read your updated question. Since you're running into login issues, try doing this before you execute the request:
request.Credentials = CredentialCache.DefaultCredentials
If this doesn't work, then perhaps the problem is that authentication is not being enforced on static files, but is being enforced on dynamic files. In this case, you'll need to log in first (using your client code) and retain the login cookie (using HttpWebRequest.CookieContainer on the login request as well as on the second request) or turn off authentication on the page you're trying to access.
ORIGINAL:
Since it works with one HTTP URL and doesn't work with another, the place to start diagnosing this is figuring out what's different between the two requests, at the HTTP level, which accounts for the difference in behavior in your code.
To figure out the difference, I'd use Fiddler (http://fiddlertool.com) to compare the two requests. Compare the HTTP headers. Are they the same? In particular, are they the same HTTP content type? If not, that's likely the source of your problem.
If headers are the same, make sure both the static and dynamic image are exactly the same content and file type on the server. (e.g. use File...Save As to save the image in a browser to your disk). Then use Fiddler's Hex View to compare the image content. Can you see any obvious differences?
Finally, I'm sure you've already checked this, but just making sure: /Publication/render_citation_chart.aspx refers to an actual image file, not an HTML wrapper around an IMG element, right? This would account for the behavior you're seeing, where a browser renders the image OK but your code doesn't.

Categories