how to make bar-code label from encrypted text - c#

i am using USPS service. when i sent request for tracking label i got out put of encrypted text now i should make that encrypted text to bar code label.
I have tried following code but did not get any result. i C# (ASP.net) i am using
System.Drawing.Image newImage;
string str = "JVBERi0xLjINCjUgMCBvYmoNCjw8DQovVHlwZSAvWE9iamVjdA0KL1N1YnR5cGUg....";
byte[] arr = System.Text.Encoding.ASCII.GetBytes(str);
string strFileName = GetTempFolderName() + "yourfilename.gif";
if (byteArrayIn != null)
{
using (MemoryStream stream = new MemoryStream(byteArrayIn))
{
newImage = System.Drawing.Image.FromStream(stream);
newImage.Save(strFileName);
Image11.Attributes.Add("src", strFileName);
}
}
}
Please help me if you have any solution
Regards
sanjay

Related

How can i save to clipboard an image in base64?

I'm trying to save to clipboard an image in base64. But i can't find methods to do it. I can get the base64 string and save it, but not an Image :
public void GetUrl(ExportEventArgs Args)
{
string dataURL = Args.DataUrl;
//byte[] bytes = Convert.FromBase64String(dataURL);
//System.Drawing.Image image;
//using (MemoryStream ms = new MemoryStream(bytes))
//{
// image = System.Drawing.Image.FromStream(ms);
//}
Clipboard.SetTextAsync(dataURL);
}
I'm using .NET MAUI Blazor and the Clipboard class is Microsoft.Maui.ApplicationModel.DataTransfer.Clipboard but i can't find how do it.
Thanks :)

Server for displaying pictures in web browser

What I am trying to do is send a picture from the server to the client (web browser). So when I open the link in the browser, for example https://localhost:8080/geoserver/ (I set the port to 8080 at the beginning) it will display the message "hello world" which is fine but now I am trying to send image with the StreamWriter and all I got was some text like System.Drawing.Bitmap and there was no picture displayed in the browser. Im working with c# console application.
My code:
static void Main(string[] args)
{
HttpListener listen = new HttpListener();
string url = "http://localhost";
string port = "";
Console.Write("Nastavite port:");
port = Console.ReadLine();
url = url + ":" + port + "/geoserver/";
listen.Prefixes.Add(url);
listen.Start();
while (true)
{
Console.WriteLine("Cakam...");
HttpListenerContext kontekst = listen.GetContext();
string msg = "hello world";
kontekst.Response.ContentLength64 = Encoding.UTF8.GetByteCount(msg);
kontekst.Response.StatusCode = (int)HttpStatusCode.OK;
using(Stream stream = kontekst.Response.OutputStream)
{
using(StreamWriter writer = new StreamWriter(stream))
{
writer.Write(msg);
}
}
Console.WriteLine("Sporočilo poslano");
}
}
You can do it, by converting the image to base64 and display it in a html img tag.
1) Use the System.Drawing library to get the picture as a byte array
Image image = Image.FromFile("test-img.jpg");
MemoryStream ms = new MemoryStream();
image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] imgBytes = ms.ToArray();
2) After you need to convert it to a base64 string
string base64 = Convert.ToBase64String(imgBytes);
3) Then you create the html response text
string html = $"<html><img src=\"data: image / png; base64, {base64} \"></html>";
4) Now you can write this text to the output stream
Stream stream = kontekst.Response.OutputStream;
StreamWriter writer = new StreamWriter(stream);
writer.WriteLine(html);
So the full working code looks like this
static void Main(string[] args)
{
HttpListener listen = new HttpListener();
string url = "http://localhost";
string port = "";
Console.Write("Nastavite port:");
port = Console.ReadLine();
url = url + ":" + port + "/geoserver/";
listen.Prefixes.Add(url);
listen.Start();
while (true)
{
Console.WriteLine("Cakam...");
HttpListenerContext kontekst = listen.GetContext();
kontekst.Response.StatusCode = (int)HttpStatusCode.OK;
using (Stream stream = kontekst.Response.OutputStream)
using (Image image = Image.FromFile("test-img.jpg"))
using (MemoryStream ms = new MemoryStream())
using (StreamWriter writer = new StreamWriter(stream))
{
image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
string base64 = Convert.ToBase64String(ms.ToArray());
writer.WriteLine($"<html><img src=\"data: image / png; base64, {base64} \"></html>");
}
Console.WriteLine("Sporočilo poslano");
}
}
The minimal changes required to make your code work is to use the Save method to write the image to the stream, instead of Writer.Write(), which will call the ToString() of the object, (if it's not already a character array) resulting in sending the class name that you experienced.
//Can't set the response length upfront, if you really need to set it you need to
//calculate it from the size of the image.
//kontekst.Response.ContentLength64 = Encoding.UTF8.GetByteCount(msg);
//Most browsers figure it out without this, but good practice to set the type:
kontekst.Response.ContentType = "image/bmp";
kontekst.Response.StatusCode = (int)HttpStatusCode.OK;
var img = Image.FromFile(#"some.bmp");
using (Stream stream = kontekst.Response.OutputStream)
{
img.Save(stream, ImageFormat.Bmp);
}
I would also consider changing some other things:
Instead of System.Drawing.Bitmap, use System.Drawing.Image as I did if you don't need to edit the image on the server. Or even better, if you don't need to treat it as an image on the server side, just read it in with a FileStream and write it out to the Output stream.
Do you really want to implement your on server and deal with the low level HttpContext / listeners? Maybe you could use ASP.Net Core with Kestrel.

Upload Image to a Chevereto Website C#

A friend of my is trying to upload a image on a Windows Form App to a chevereto website, using chevereto API and trying to get the link back(response from website), but its not really working...
API: Chevereto API
UPDATE: Code Added
static class Upload
{
string apiKey = "DEFAULT_API_KEY";
public string UploadImage(Image image)
{
WebClient webClient = new WebClient();
webClient.Headers.Add("key", apiKey);
webClient.Headers.Add("format", "txt");
System.Collections.Specialized.NameValueCollection Keys =
new System.Collections.Specialized.NameValueCollection();
try
{
string ht = "http://";
Keys.Add("image", ImageToBase64(image, ImageFormat.Bmp));
byte[] responseArray = webClient.UploadValues(ht + "mysite.com/api/1/upload/", Keys);
string result = Encoding.ASCII.GetString(responseArray);
return result;
}
catch (Exception e)
{
InternalConsole.LogError("Cannot upload image, error on next line: ");
InternalConsole.Log(e.Message);
return "none";
}
}
public string ImageToBase64(Image image, System.Drawing.Imaging.ImageFormat format)
{
using (MemoryStream ms = new MemoryStream())
{
// Convert Image to byte[]
image.Save(ms, format);
byte[] imageBytes = ms.ToArray();
// Convert byte[] to Base64 String
string base64String = Convert.ToBase64String(imageBytes);
return base64String;
}
}
}
Can someone show me how its done?
Thanks in advance.
Nevermind guys, my friend already fixed the problem.
He used WebRequest to send and receive the data.
He also said, dont forget to escape the string of base64(+, =, /), or the api will not accept properly and will return invalid base64 string.
Thanks anyway.

Convert ImageSource to Base64String - WP8

am working on WP8application, I have few images in location Resources\Graphics\ i am trying to display images from these folder, but its not picking the path.
Here is my code :
<img src=\"/Resources;component/Graphics/"+ImageName).Append("\" ") this is in my string which i am using in my WebBrowserControl.
WebBrowserControl.NavigateToString(html); // here html is a string which has all the html code in it.
But its not display the images.
So i want to convert the ImageSource --Resources;component/Graphics/"+ImageName to Base64String how to do it?
I have looked into many examples but none of them is compatible for WP8.
You can get StreamInfo by using this:
Application.GetResourceStream(new Uri("Resources;component/Graphics/"+ImageName", System.UriKind.Relative));
Then you can read this stream into an byte array. After that, use Convert.ToBase64String() to get what you want. Try this. Maybe you can read the MSDN document to find how to use Stream.
var img = Application.GetResourceStream(new Uri("Resources;component/Graphics/"+ImageName", System.UriKind.Relative));
var buffer = new byte[img.Stream.Length];
img.Stream.Seek(0, SeekOrigin.Begin);
img.Stream.Read(buffer, 0, buffer.Length);
var base64 = Convert.ToBase64String(buffer);
It's very simple - load your image into a byte array and call
System.Convert.ToBase64String(imageArray).
That being said, this will not result in displaying the image. The NavigateToString requires html. See documentation
This is my code
byte[] bytearray = null;
using (var ms = new MemoryStream())
{
if (bmp != null)
{
var wbitmp = new WriteableBitmap(bmp);
wbitmp.SaveJpeg(ms, 46, 38, 0, 100);
bytearray = ms.ToArray();
}
}
if (bytearray != null)
{
// image base64 here
string btmStr = Convert.ToBase64String(bytearray);
}

converting a base 64 string to an image and saving it

Here is my code:
protected void SaveMyImage_Click(object sender, EventArgs e)
{
string imageUrl = Hidden1.Value;
string saveLocation = Server.MapPath("~/PictureUploads/whatever2.png") ;
HttpWebRequest imageRequest = (HttpWebRequest)WebRequest.Create(imageUrl);
WebResponse imageResponse = imageRequest.GetResponse();
Stream responseStream = imageResponse.GetResponseStream();
using (BinaryReader br = new BinaryReader(responseStream))
{
imageBytes = br.ReadBytes(500000);
br.Close();
}
responseStream.Close();
imageResponse.Close();
FileStream fs = new FileStream(saveLocation, FileMode.Create);
BinaryWriter bw = new BinaryWriter(fs);
try
{
bw.Write(imageBytes);
}
finally
{
fs.Close();
bw.Close();
}
}
}
The top imageUrl declartion is taking in a Base64 image string, and I want to convert it into an image. I think my set of code only works for images like "www.mysite.com/test.jpg" not for a Base64 string. Anybody have some suggestions? Thanks!
Here is an example, you can modify the method to accept a string parameter. Then just save the image object with image.Save(...).
public Image LoadImage()
{
//data:image/gif;base64,
//this image is a single pixel (black)
byte[] bytes = Convert.FromBase64String("R0lGODlhAQABAIAAAAAAAAAAACH5BAAAAAAALAAAAAABAAEAAAICTAEAOw==");
Image image;
using (MemoryStream ms = new MemoryStream(bytes))
{
image = Image.FromStream(ms);
}
return image;
}
It is possible to get an exception A generic error occurred in GDI+. when the bytes represent a bitmap. If this is happening save the image before disposing the memory stream (while still inside the using statement).
You can save Base64 directly into file:
string filePath = "MyImage.jpg";
File.WriteAllBytes(filePath, Convert.FromBase64String(base64imageString));
Here is what I ended up going with.
private void SaveByteArrayAsImage(string fullOutputPath, string base64String)
{
byte[] bytes = Convert.FromBase64String(base64String);
Image image;
using (MemoryStream ms = new MemoryStream(bytes))
{
image = Image.FromStream(ms);
}
image.Save(fullOutputPath, System.Drawing.Imaging.ImageFormat.Png);
}
I would suggest via Bitmap:
public void SaveImage(string base64)
{
using (MemoryStream ms = new MemoryStream(Convert.FromBase64String(base64)))
{
using (Bitmap bm2 = new Bitmap(ms))
{
bm2.Save("SavingPath" + "ImageName.jpg");
}
}
}
Here is working code for converting an image from a base64 string to an Image object and storing it in a folder with unique file name:
public void SaveImage()
{
string strm = "R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7";
//this is a simple white background image
var myfilename= string.Format(#"{0}", Guid.NewGuid());
//Generate unique filename
string filepath= "~/UserImages/" + myfilename+ ".jpeg";
var bytess = Convert.FromBase64String(strm);
using (var imageFile = new FileStream(filepath, FileMode.Create))
{
imageFile.Write(bytess, 0, bytess.Length);
imageFile.Flush();
}
}
In my case it works only with two line of code. Test the below C# code:
String dirPath = "C:\myfolder\";
String imgName = "my_mage_name.bmp";
byte[] imgByteArray = Convert.FromBase64String("your_base64_string");
File.WriteAllBytes(dirPath + imgName, imgByteArray);
That's it. Kindly up vote if you really find this solution works for you. Thanks in advance.
In a similar scenario what worked for me was the following:
byte[] bytes = Convert.FromBase64String(Base64String);
ImageTagId.ImageUrl = "data:image/jpeg;base64," + Convert.ToBase64String(bytes);
ImageTagId is the ID of the ASP image tag.
If you have a string of binary data which is Base64 encoded, you should be able to do the following:
byte[] encodedDataAsBytes = System.Convert.FromBase64String(encodedData);
You should be able to write the resulting array to a file.
public bool SaveBase64(string Dir, string FileName, string FileType, string Base64ImageString)
{
try
{
string folder = System.Web.HttpContext.Current.Server.MapPath("~/") + Dir;
if (!Directory.Exists(folder))
{
Directory.CreateDirectory(folder);
}
string filePath = folder + "/" + FileName + "." + FileType;
File.WriteAllBytes(filePath, Convert.FromBase64String(Base64ImageString));
return true;
}
catch
{
return false;
}
}
Using MemoryStream is not a good idea and violates a specification in MSDN for Image.FromStream(), where it says
You must keep the stream open for the lifetime of the Image.
A better solution is using ImageConverter, e.g:
public Image ConvertBase64ToImage(string base64)
=> (Bitmap)new ImageConverter().ConvertFrom(Convert.FromBase64String(base64));
In NetCore 6.0, you can use HttpClient and the async methods in the new File class.
The implementation is very simple:
static async Task DownloadFile(string imageUrl, string pathToSave)
{
var content = await GetUrlContent(url);
if (content != null)
{
await File.WriteAllBytesAsync(pathToSave, content);
}
}
static async Task<byte[]?> GetUrlContent(string url)
{
using (var client = new HttpClient())
using (var result = await client.GetAsync(url))
return result.IsSuccessStatusCode ? await result.Content.ReadAsByteArrayAsync():null;
}
Usage:
await DownloadFile("https://example.com/image.jpg", #"c:\temp\image.jpg");

Categories