I am generating a QR Code and I am trying to get it as a SVG so I can display it in an email.
My part of the code I am having issues with is this:
using (Bitmap bitMap = qrCode.GetGraphic(20))
{
using (MemoryStream ms = new MemoryStream())
{
bitMap.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
byte[] byteImage = ms.ToArray();
imgBarCode.ImageUrl = "data:image/png;base64," + Convert.ToBase64String(byteImage);
}
}
I am trying to convert imgBarCode.ImageUrl to SVG, but I have no idea how to do this, any help would be appreciated.
Related
I have a problem with my webSite, I must create one image file for every record in my app.
In my IDE works fine, but I tested it in the IIS and I can't create the image files and I get the Generic Error GDI (System.Runtime.InteropServices.ExternalException)
The image folder have all W/R permissions, this is my Image Generator:
private void generador(string barCode)
{
using (Bitmap bitMap = new Bitmap(barCode.Length * 40, 80))
{
using (Graphics graphics = Graphics.FromImage(bitMap))
{
// IDAHC39M Code 39 Barcode INSTALADO en los fonts del servidor
Font oFont = new Font("IDAHC39M Code 39 Barcode", 16);
PointF point = new PointF(2f, 2f);
SolidBrush blackBrush = new SolidBrush(Color.Black);
SolidBrush whiteBrush = new SolidBrush(Color.White);
graphics.FillRectangle(whiteBrush, 0, 0, bitMap.Width, bitMap.Height);
graphics.DrawString("*" + barCode + "*", oFont, blackBrush, point);
bitMap.Save(HttpContext.Current.Server.MapPath("/codigos/" + barCode + ".png"), ImageFormat.Png);
bitMap.Dispose();
}
}
}
I have my data in a DataTable (just for testing) and when I iterate (calling repeatly generator), I have that error.
I repeat, in my IDE works perfectly, but when te application is published, I have this problem.
Please, anybody can help me?
thanks in advance.
best regards.
As Lex Li said: "System.Drawing is not supported in web apps", Using it cause a LOT of problems. So I decided to use NetBarCode, and I could make it work:
- Install NetBarCode from nuget
- This is the code:
using NetBarcode; //Instalar NetBarcode de NugetPackages o usar la dll
using System.IO; // Filestream
using System.Configuration;
using System.Data;
private void generador(string codigo)
{
var barcode = new Barcode("*" + codigo.Trim() + "*", NetBarcode.Type.Code39, true);
var value = barcode.GetBase64Image();
string filepath = Server.MapPath("~/codigos/" + codigo.Trim() + ".jpeg"); //Generar archivo
var bytess = Convert.FromBase64String(value);
using (var imageFile = new FileStream(filepath, FileMode.Create))
{
imageFile.Write(bytess, 0, bytess.Length);
imageFile.Flush();
}
}
protected void Bucle(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add("Nif");
dt.Columns.Add("Estudiante");
dt.Columns.Add("Titulo");
// Emulating my data
// dt.Rows.Add("01769459"......)
foreach (DataRow row in dt.Rows)
{
generador(row["Nif"].ToString());
}
}
But if you want, you must control the memory stream, example (simliar), I use QRCoder.dll for it:
protected void Generar(string nif, string fileName)
{
QRCodeGenerator qrGenerador = new QRCodeGenerator();
QRCodeGenerator.QRCode qrCode = qrGenerador.CreateQrCode(nif, QRCodeGenerator.ECCLevel.Q);
System.Web.UI.WebControls.Image imgQrCode = new System.Web.UI.WebControls.Image();
imgQrCode.Height = 150;
imgQrCode.Width = 150;
string filepath = Server.MapPath("~/files/" + fileName.Trim() + ".jpeg"); //Generar archivo
Bitmap bitmap = qrCode.GetGraphic(20);
using (MemoryStream memory = new MemoryStream())
{
using (FileStream fs = new FileStream(filepath, FileMode.Create, FileAccess.ReadWrite))
{
bitmap.Save(memory, ImageFormat.Jpeg);
byte[] bytes = memory.ToArray();
fs.Write(bytes, 0, bytes.Length);
}
}
}
I create an asp.net 4.0 web application which has a web service for uploading images. I am uploading images by sending the image in form of Base64 string from my mobile app to the web service.
Following is my code:
public string Authenticate(string username, string password, string fileID, string imageData)
{
Dictionary<string, string> responseDictionary = new Dictionary<string, string>();
bool isAuthenticated = true; // Set this value based on the authentication logic
try
{
if (isAuthenticated)
{
UploadImage(imageData);
string result = "success";
var message = "Login successful";
responseDictionary["status"] = result;
responseDictionary["message"] = message;
}
}
catch (Exception ex)
{
responseDictionary["status"] = ex.Message;
responseDictionary["message"] = ex.StackTrace;
}
return new JavaScriptSerializer().Serialize(responseDictionary);
}
private void UploadImage(string uploadedImage)
{
// Convert Base64 String to byte[]
byte[] imageBytes = Convert.FromBase64String(uploadedImage);
MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);
System.Drawing.Bitmap bitmap = (System.Drawing.Bitmap)Image.FromStream(ms);
string uploadPath = Server.MapPath("..\\uploads\\") + DateTime.Now.Ticks.ToString() + ".jpeg";
ms.Close();
bitmap.Save(uploadPath, System.Drawing.Imaging.ImageFormat.Jpeg);
bitmap.Dispose();
}
This code was working fine on my local ASP.NET development server and I was able to see the uploaded image in my "uploads" directory. However, after transferring the code to the FTP directory, I am now getting the following error:
A generic error occurred in GDI+
I have checked that the upload directory has proper permission by creating a dummy .aspx page and creating a text file on page_load, and it works fine.
Even after doing google search, I was not able to solve this problem. Can anybody help me fixing this?
Thanks a lot in advance.
Instead of writing directly to files, save your bitmap to a MemoryStream and then save the contents of the stream to disk. This is an old, known issue and, frankly, I don't remember all the details why this is so.
MemoryStream mOutput = new MemoryStream();
bmp.Save( mOutput, ImageFormat.Png );
byte[] array = mOutput.ToArray();
// do whatever you want with the byte[]
In your case it could be either
private void UploadImage(string uploadedImage)
{
// Convert Base64 String to byte[]
byte[] imageBytes = Convert.FromBase64String(uploadedImage);
string uploadPath = Server.MapPath("..\\uploads\\") + DateTime.Now.Ticks.ToString() + ".jpeg";
// store the byte[] directly, without converting to Bitmap first
using ( FileStream fs = File.Create( uploadPath ) )
using ( BinaryWriter bw = new BinaryWriter( fs ) )
bw.Write( imageBytes );
}
or
private void UploadImage(string uploadedImage)
{
// Convert Base64 String to byte[]
byte[] imageBytes = Convert.FromBase64String(uploadedImage);
MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);
System.Drawing.Bitmap bitmap = (System.Drawing.Bitmap)Image.FromStream(ms);
string uploadPath = Server.MapPath("..\\uploads\\") + DateTime.Now.Ticks.ToString() + ".jpeg";
ms.Close();
// convert to image first and store it to disk
using ( MemoryStream mOutput = new MemoryStream() )
{
bitmap.Save( mOutput, System.Drawing.Imaging.ImageFormat.Jpeg);
using ( FileStream fs = File.Create( uploadPath ) )
using ( BinaryWriter bw = new BinaryWriter( fs ) )
bw.Write( mOutput.ToArray() );
}
}
Furthermore I think it's worth pointing out that when MemoryStream is used, stream must always be closed and save method MUST be called before the stream closure
byte[] byteBuffer = Convert.FromBase64String(Base64String);
MemoryStream memoryStream = new MemoryStream(byteBuffer);
memoryStream.Position = 0;
Bitmap bmpReturn = (Bitmap)Bitmap.FromStream(memoryStream);
bmpReturn.Save(PicPath, ImageFormat.Jpeg);
memoryStream.Close();
I need to save base64string to image in local path. The following are the code I used.
byte[] bytes = Convert.FromBase64String(hdnBase64.Value.Split(',')[1]);
System.Drawing.Image image;
using (MemoryStream ms = new MemoryStream(bytes))
{
image = System.Drawing.Image.FromStream(ms);
image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
//image.Save("C:\\test.png");
}
string filename = DateTime.Now.ToString("yyyyMMddHHmmssfff");
string path = Path.Combine(Server.MapPath("~/Temp"), filename + ".png");
image.Save(path);
imgBrowse.Attributes.Add("src", path);
hdnBase64 is a hiddenfield which contain base64 image. while executing I got the generic error. please help me out to solve this problem!
Thanks in advance,
Ganesh M
You have to include the Save(path) call in the using section.
You've created the image from a MemoryStream object, which is automatically disposed once you exit from the using block.
byte[] bytes = Convert.FromBase64String(hdnBase64.Value.Split(',')[1]);
System.Drawing.Image image;
using (MemoryStream ms = new MemoryStream(bytes))
{
image = System.Drawing.Image.FromStream(ms);
image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
string filename = DateTime.Now.ToString("yyyyMMddHHmmssfff");
string path = Path.Combine(Server.MapPath("~/Temp"), filename + ".png");
image.Save(path);
}
imgBrowse.Attributes.Add("src", path);
my code for convert image to byte but i m getting black screen in image box:
Bitmap bitmap = new Bitmap(100, 100);
MemoryStream MemImage = new MemoryStream();
bitmap.Save(name, ImageFormat.Bmp);
bitmap.Save(MemImage, ImageFormat.Bmp);
byte[] Byte = MemImage.ToArray();
Convert byte to image :
byte[] data = (byte[])Query.Images;
MemoryStream strm = new MemoryStream();
strm.Write(data, 0, data.Length);
strm.Position = 0;
System.Drawing.Image imgTemp = System.Drawing.Image.FromStream(strm);
BitmapImage bi = new BitmapImage();
bi.BeginInit();
MemoryStream ms = new MemoryStream();
imgTemp.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
ms.Seek(0, SeekOrigin.Begin);
bi.StreamSource = ms;
bi.EndInit();
ImageBox.Source = bi;
But in the above code one problem is image is not show in image box (show black screen)
please solve this problem and send me.....Thanks
Try this code
public byte[] imageToByteArray(System.Drawing.Image imageIn)
{
MemoryStream ms = new MemoryStream();
imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
return ms.ToArray();
}
public Image byteArrayToImage(byte[] byteArrayIn)
{
MemoryStream ms = new MemoryStream(byteArrayIn);
Image returnImage = Image.FromStream(ms);
return returnImage;
}
I use Sharepoint 2010 and I am developing a web part where on a button click event, a pdf file needs to be generated and opened directly. Should not be saving onto the disk.
I tried the below code
protected void Button1_OnClick(object sender, EventArgs e)
{
Document myDoc = new Document(PageSize.A4.Rotate());
try
{
PdfWriter.GetInstance(myDoc, new FileStream(#"C:\Directory\Test.pdf", FileMode.Create));
myDoc.Open();
myDoc.Add(new Paragraph("Hello World"));
}
catch (DocumentException ex)
{
Console.Error.WriteLine(ex.Message);
}
myDoc.Close();
}
I also tried the below code which also generates the file on the Server which I dont want.
Document document = new Document(PageSize.A4);
PdfWriter.GetInstance(document, new FileStream(HttpContext.Current.Server.MapPath("~/Test.pdf"), FileMode.Create));
document.Open();
var WelcomePara = new Paragraph("Hello World");
document.Add(WelcomePara);
document.Close();
This one creates the pdf file on the desktop, I need it to be opened in the pdf format.Can someone help me please.
Almost every time that something accepts a FileStream is actually really accepts a generic System.IO.Stream object which FileStream is a subclass of. This means that you can instead use its cousin System.IO.MemoryStream which is what you are looking for:
byte[] bytes;
using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) {
using (iTextSharp.text.Document doc = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4.Rotate())) {
using (iTextSharp.text.pdf.PdfWriter w = iTextSharp.text.pdf.PdfWriter.GetInstance(doc, ms)) {
doc.Open();
doc.NewPage();
doc.Add(new iTextSharp.text.Paragraph("Hello world"));
doc.Close();
bytes = ms.ToArray();
}
}
}
//Do whatever you want with the byte array here
You don't have to create the byte array if you don't want, I was just showing how to create a PDF and give you something ".net-like" for you to work with.
I was able to get it work finally.
using (var ms = new MemoryStream())
{
using (var document = new Document(PageSize.A4,50,50,15,15))
{
PdfWriter.GetInstance(document, ms);
document.Open();
document.Add(new Paragraph("HelloWorld"));
document.Close();
}
Response.Clear();
//Response.ContentType = "application/pdf";
Response.ContentType = "application/octet-stream";
Response.AddHeader("content-disposition", "attachment;filename= Test.pdf");
Response.Buffer = true;
Response.Clear();
var bytes = ms.ToArray();
Response.OutputStream.Write(bytes, 0, bytes.Length);
Response.OutputStream.Flush();
}
This Works for me.
using (var ms = new MemoryStream())
{
using (var document = new Document(PageSize.A4,50,50,15,15))
{
// step 2
PdfWriter writer = PdfWriter.GetInstance(document, ms);
// step 3
document.Open();
// XML Worker
XMLWorker worker = new XMLWorker(css, true);
XMLParser p = new XMLParser(worker);
p.Parse(new StringReader(--Your HTML--));
// step 5
document.Close();
}
Byte[] FileBuffer = ms.ToArray();
if (FileBuffer != null)
{
Response.ContentType = "application/pdf";
Response.AddHeader("content-length", FileBuffer.Length.ToString());
Response.BinaryWrite(FileBuffer);
}
}