Convert image url into image bye in asp.net - c#

for (int i = 0; i < (DataTable)ViewState["Table_RemarksDetails"]).Rows.Count; i++)
{
string url = Image1.ImageUrl;
Byte[] imgByte = GetBytesFromUrl(url);
obj_ICCommon.Userid = username;
obj_ICCommon.Modules = "Transfer-TO";
obj_ICCommon.Invoiceno = TransferNo;
obj_ICCommon.Comments = ((DataTable)ViewState["Table_RemarksDetails"]).Rows[i]["Comments"].ToString();
//obj_ICCommon.Image = imgByte;
string Result = obj_ICCommon.funinsertRemarks();
fun_InsertRemarksImage(TransferNo, imgByte, ((DataTable)ViewState["Table_RemarksDetails"]).Rows[i]["Comments"].ToString());
}
static public byte[] GetBytesFromUrl(string url)
{
byte[] b;
System.Net.HttpWebRequest myReq = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
System.Net.WebResponse myResp = myReq.GetResponse();
Stream stream = myResp.GetResponseStream();
//int i;
using (BinaryReader br = new BinaryReader(stream))
{
//i = (int)(stream.Length);
b = br.ReadBytes(500000);
br.Close();
}
myResp.Close();
return b;
}
This code throws an exception url not recognized. My url is in format like "data://image.png" . What to do ? Anyone lets you know. I am struggle in this past 2 days.
I just want to convert the url into byte
. If my code is wrong or any other way is possible to convert url into byte. Please comment me. Thanks in advance

If you want to turn a data URI into a byte image, your input string is not sufficient. Given the following sample data URI:
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=="
You would need to:
Trim the data: string from the front.
Split by the ; character to get the image format and encoding type.
If the encoding type is Base64, you would need to use the data obtained in (2) to decode the image string back into a byte array.
If on the other hand, you want to change the image data.png into its corresponding base64 representation, then you would need to make some changes to your code:
Decide what URL's you are going to be reading. If they are web, such as http and https, then your code should be good since you are dealing with web requests. If they are actual file paths, you would need to handle the file URI, so your code would be slightly different.
One that you will have your file, you would need to load it as a byte array.
Create a string with the following: data:image/png;base64,.
Append the base64 representation of the byte array you got in step 2.

Related

Best way to transform string to valid encoding in C#

Sorry in advance if you have a duplicate or a simple question! I can't find the answer.
I'm working with a dll made in Delphi. Data can be sent to the device using a DLL. However, at the time the data is sent, some strings are not accepted or are written blank. The data sent to the device is stored in a txt file. It was generated using txt file third party program.
That is, I think the string is in an indefinite format. If I send in utf-8 format, it receives all the information. But some strings at the time ???? ???? remains.
Many of my texts are in the Cyrillic alphabet.
What I did:
// string that send to device
[MarshalAsAttribute(UnmanagedType.LPStr, SizeConst = 36)]
public string Name;
When I did this, the device received only 10 out of 100 data.
If i encoding with UTF-8:
byte[] bytes = Encoding.Default.GetBytes(getDvsName[1].ToString());
string res = Encoding.UTF8.GetString(bytes);
Got all the data this way but too many strings are became as ??? ????.
Also i tried like this:
static private string Win1251ToUTF8(string source)
{
Encoding utf8 = Encoding.GetEncoding(«utf-8»);
Encoding win1251 = Encoding.GetEncoding(«windows-1251»);
byte[] utf8Bytes = win1251.GetBytes(source);
byte[] win1251Bytes = Encoding.Convert(win1251, utf8, utf8Bytes);
source = win1251.GetString(win1251Bytes);
return source;
}
All of the above methods did not help. How can I receive incoming information in the correct format? Are there other ways?
hi there here is what went wrong you did encode the string to default instead of utf8.
string tom = "ටොම් හැන්ක්ස්";
byte[] bytes = Encoding.UTF8.GetBytes(tom);
string res = Encoding.UTF8.GetString(bytes);

Getting empty pdf attachments when trying to create "activitymimeattachment"

I want to attach pdf from url into CRM "activitymimeattachment". Everything works fine but im getting empty pdf attachments (even the size is the same as original pdf). Could it be some problem with Encoding or converting? Maybe somebody could help me with this?
I see that email is created with attachment which is empty, but the size is the same as for original pdf.
Entity attachment = new Entity("activitymimeattachment");
attachment["subject"] = "Attachment";
string fileName = "Invoice.pdf";
attachment["filename"] = fileName;
WebClient wc = new WebClient();
string theTextFile = wc.DownloadString(url);
byte[] fileStream = Encoding.ASCII.GetBytes(theTextFile);
attachment["body"] = Convert.ToBase64String(fileStream);
attachment["mimetype"] = "application/pdf";
attachment["attachmentnumber"] = 1;
attachment["objectid"] = new EntityReference("email", emailguid);
attachment["objecttypecode"] = "email";
service.Create(attachment);
I believe the encoding is issue. The PDF is neither a string nor an ASCII file so these lines are at fault:
string theTextFile = wc.DownloadString(url);
byte[] fileStream = Encoding.ASCII.GetBytes(theTextFile);
I would suggest changing your web client to download a binary file i.e. application/pdf and save the file locally e.g to d:\temp\invoice.pdf.
Then you can do this:
var bytes = File.ReadAllBytes(#"d:\temp\invoice.pdf");
var body = Convert.ToBase64String(bytes);
In short, avoid trying to put the PDF into a string, or using the ASCII encoding to get its byte array. It's a binary file until you convert it to Base64.
Of course you can also probably get your web client to download the file into memory and convert it to Base64 without writing the file locally. I just wanted the simplest example to make the point about the encoding.
Thank You for advice #Aron. I actually have found a solution which is very simnply. I just used another method from WebClient class. The main thing I needed to change DownloadString(url) method into DownloadData(url) method:
WebClient wc = new WebClient();
byte[] theTextFile = wc.DownloadData(url);
attachment["body"] = Convert.ToBase64String(theTextFile);enter code here

Why UTF-8 fail on this encoding?

I'm about to download a page encoded in UTF-8.
So this is my code:
using (WebClient client = new WebClient())
{
client.Headers.Add("user-agent", Request.UserAgent);
htmlPage = client.DownloadString(HttpUtility.UrlDecode(resoruce_url));
var KeysParsed = HttpUtility.ParseQueryString(client.ResponseHeaders["Content-Type"].Replace(" ", "").Replace(";", "&"));
var charset = ((KeysParsed["charset"] != null) ? KeysParsed["charset"] : "UTF-8");
Response.Write(client.ResponseHeaders);
byte[] bytePage = Encoding.GetEncoding(charset).GetBytes(htmlPage);
using (var reader = new StreamReader(new MemoryStream(bytePage), Encoding.GetEncoding(charset)))
{
htmlPage = reader.ReadToEnd();
Response.Write(htmlPage);
}
}
so, it set UTF-8 for the encoding. But the downloaded title, for example, show in my screen as:
Sexy cover: 60 e più di “quei dischi” vietati ai minori
and not as:
Sexy cover: 60 e più di “quei dischi” vietati ai minori
somethings is wrong, but I don't find where. Any ideas?
The problem is that by the time you get the data it's already been converted.
When WebClient.DownloadString executes, it gets the raw bytes and converts them to a string using the default encoding. The damage is done. You can't take the resulting string, turn it back into bytes, and re-interpret it.
Put another way, this is what's happening:
// WebClient.DownloadString does, essentially, this.
byte[] rawBytes = DownloadData();
string htmlPage = Encoding.Default.GetString(rawBytes);
// Now you're doing this:
byte[] myBytes = Encoding.Utf8.GetBytes(htmlPage);
But myBytes will not necessarily be the same as rawBytes.
If you know what encoding to use beforehand, you can set the WebClient instance's Encoding property. If you want to interpret the string based on the encoding specified in the Content-Type header, then you have to download the raw bytes, determine the encoding, and use that to interpret the string. For example:
var rawBytes = client.DownloadData(HttpUtility.UrlDecode(resoruce_url));
var KeysParsed = HttpUtility.ParseQueryString(client.ResponseHeaders["Content-Type"].Replace(" ", "").Replace(";", "&"));
var charset = ((KeysParsed["charset"] != null) ? KeysParsed["charset"] : "UTF-8");
var theEncoding = Encoding.GetEncoding(charset);
htmlPage = theEncoding.GetString(rawBytes);

Saving HTML of img/image to Disk

I have a div with an image inside of it. In javascript I am getting the div, and sending the innerHTML of the div to the server. The javascript is oversimplified below:
function uploadImage() {
var imageInfo = document.getElementById('divImage').innerHTML;
PageMethods.uploadImage(imageInfo, onSuccess, onError);
} //end function
I am currently receiving this on the server as a string.
[WebMethod]
public static string uploadImage(string base64FileString){...}
The results are as follows:
<img height="150" width="150" title="name.png" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAA...../>
I need to save this image to disk, and I'm at a loss. It's my understanding that I could get everything past the "base64," (using a split) and create an image using the following:
// Convert Base64 String to byte[]
byte[] imageBytes = Convert.FromBase64String(base64FileString);
MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);
// Convert byte[] to Image
ms.Write(imageBytes, 0, imageBytes.Length);
System.Drawing.Image image = System.Drawing.Image.FromStream(ms, true);
image.Save(.....);
But this seems very inefficient. Is there a better way to create the image from the string, a better way to receive the string, or better way to pass the string?
You can use File.WriteAllBytes:
byte[] imageBytes = Convert.FromBase64String(base64FileString);
File.WriteAllBytes(path, imageBytes);
Absolutely no need to go through MemoryStream and the System.Drawing namespace once you have the byte[].
I know there must be a better way to do this, but I have a solution that at least works. If anyone can point out a more sophisticated way I'm all ears. I would have assumed there was some sort of object that would receive the img on the server to save to disk, but maybe not.
Javascript and webmethod remain unchanged. I passed the InnerHTML of the div to the server, and accept it as a string. On the server I used multiple splits (which I understand to be very slow) to get at the base64 part of the image.
[WebMethod]
public static string uploadImage(string base64FileString){
//Get all of the text right of the comma
string base64PartTemp= base64FileString.Split(',')[1];
//The final part of the base64 had a \" to remove
//Now base64PartFinal is the base64 part of the image only
string base64PartFinal= base64PartTemp.Split('\"')[0];
//Get all of the text to the right of the period from original string
string fileTypePart = base64FileString.Split('.')[1];
//Because the file is an image the file type will be 3 chars
string fileType = fileTypePart.Substring(0, 3);
//Use a new guid for the file name, and append the fileType
string finalFileName = Guid.NewGuid() + "." + fileType;
//Turn the final base64 part into byte array
byte[] imageBytes = Convert.FromBase64String(base64PartFinal);
//Get the working directory of the project to store the files
string path= System.AppDomain.CurrentDomain.BaseDirectory.ToString();
//Append that I want to put the image in the images folder, under a designated filename
path += "Images/" + finalFileName;
//Write the image to file
File.WriteAllBytes(path, imageBytes);
...
}
I couldn't find an answer to this for a few days. I hope it helps someone. Like I said, may not be the most efficient solution, but it does work.

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

Categories

Resources