I am working on a QR Code project and one of the requirements is to be able to download the generated QR Code in SVG format. I was able to display the generated QR Code in PNG format, but I have been trying to download it in SVG format.
I am using XZing library to generate the QR Code in PNG
Color barcodeColor = System.Drawing.ColorTranslator.FromHtml(colorHex);
BarcodeWriter barcodeWriter = new BarcodeWriter
{
Format = BarcodeFormat.QR_CODE,
Options = new EncodingOptions
{
Width = width,
Height = height,
PureBarcode = true
},
Renderer = new BitmapRenderer
{
Foreground = barcodeColor
}
};
Bitmap barCodeBitmap = barcodeWriter.Write(qrContent);
var memoryStream = new MemoryStream();
// save to stream as PNG
barCodeBitmap.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Png);
HttpResponseMessage response = new HttpResponseMessage();
response.Content = new ByteArrayContent(memoryStream.ToArray());
response.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
response.StatusCode = HttpStatusCode.OK;
return response;
I was able to create a BarcodeWriterSvg object but I wasn't able to convert it into a stream and pass it in the header like the PNG
BarcodeWriterSvg barcodeWriter = new BarcodeWriterSvg
{
Format = BarcodeFormat.QR_CODE,
Options = new EncodingOptions
{
Width = width,
Height = height,
PureBarcode = true
},
Renderer = new SvgRenderer
{
Foreground = barcodeColor
}
};
var barCodeBitmap = barcodeWriter.Write(qrContent);
var memoryStream = new MemoryStream();
HttpResponseMessage response = new HttpResponseMessage();
...
My question is how to be able to convert the object into a stream and pass it in the header? The ultimate goal is to be able to download the file without actually creating a physical copy.
Off the top of my head, and attempting to use the same code paradigm from your example, I would look into something like this:
var barcodeWriter = new BarcodeWriterSvg();
....
....
var svgImage = barcodeWriter.Write(text); //ZXing.Rendering.SvgRenderer.SvgImage
var response = new HttpResponseMessage();
response.Content = new StringContent(svgImage.Content);
response.Content.Headers.ContentType = new MediaTypeHeaderValue("image/svg+xml");
return response;
Related
I'm trying to load an image into an asp image control.
That image is generated from zxing Barcode Writter.
My question is, can I load it wihtout physically saving it first?
string barcode = "xxxxxx";
BarcodeWriter writer = new BarcodeWriter() { Format = BarcodeFormat.CODE_128 };
imgBarCode.ImageUrl = writer.Write(barcode);
... How can I reference writer.Writer to image control "imgBarCode"
With the suggestion made by user1429080 I ended up with this:
string barcode = "12345"
BarcodeWriter writer = new BarcodeWriter() { Format = BarcodeFormat.CODE_128, Options = new ZXing.Common.EncodingOptions { Height = 100, Width = 300 } };
var bitmap = writer.Write(barcode);
MemoryStream ms = new MemoryStream();
bitmap.Save(ms, ImageFormat.Jpeg);
var b64 = Convert.ToBase64String(ms.ToArray());
imgBarCode.ImageUrl = "data:image/jpeg;base64," + b64;
I would like to create a QR code with using ZXing(0.16.4) But I meet following exception,
System.InvalidOperationException: 'You have to set a renderer
instance.'
Almost the same code works well with .Net Framework 4.6.1
here is my code
static void Main(string[] args)
{
var qrCode = CreateQrCode("test");
Console.ReadKey();
}
public static byte[] CreateQrCode(string content)
{
BarcodeWriter<Bitmap> writer = new BarcodeWriter<Bitmap>
{
Format = BarcodeFormat.QR_CODE,
Options = new QrCodeEncodingOptions
{
Width = 100,
Height = 100,
}
};
var qrCodeImage = writer.Write(content); // BOOM!!
using (var stream = new MemoryStream())
{
qrCodeImage.Save(stream, ImageFormat.Png);
return stream.ToArray();
}
}
I solved the issue, Basically I used https://www.nuget.org/packages/ZXing.Net.Bindings.CoreCompat.System.Drawing
I create BarcodeWriter generated from following namespace
ZXing.CoreCompat.System.Drawing
here is my CreateQrCode method
public static byte[] CreateQrCode(string content)
{
BarcodeWriter writer = new BarcodeWriter
{
Format = BarcodeFormat.QR_CODE,
Options = new QrCodeEncodingOptions
{
Width = 100,
Height = 100,
}
};
var qrCodeImage = writer.Write(content); // BOOM!!
using (var stream = new MemoryStream())
{
qrCodeImage.Save(stream, ImageFormat.Png);
return stream.ToArray();
}
}
Here is the read QR code method, maybe someone will need as well.
BarcodeReader also generated from the same namespace like create.
Here is the method
public static string ReadQrCode(byte[] qrCode)
{
BarcodeReader coreCompatReader = new BarcodeReader();
using (Stream stream = new MemoryStream(qrCode))
{
using (var coreCompatImage = (Bitmap)Image.FromStream(stream))
{
return coreCompatReader.Decode(coreCompatImage).Text;
}
}
}
Hope this answer will protect someone's hair against pulling.
There is a newer version of the package available and it works with .NET Core 3.1.
https://www.nuget.org/packages/ZXing.Net.Bindings.Windows.Compatibility/
I needed to add "Renderer = new ZXing.Rendering.BitmapRenderer()" when using ZXing.Net v0.16.6
public static byte[] CreateQrCode(string content)
{
byte[] imageData;
var qrWriter = new ZXing.BarcodeWriter<System.Drawing.Bitmap>
{
Format = BarcodeFormat.QR_CODE,
Options = new ZXing.Common.EncodingOptions { Height = 100, Width = 100, Margin = 0 },
Renderer = new ZXing.Rendering.BitmapRenderer()
};
using (var ms = new System.IO.MemoryStream())
using (System.Drawing.Bitmap pixelData = qrWriter.Write(content))
{
pixelData.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
imageData = ms.ToArray();
}
return imageData;
}
I'm currently moving to .net 6 and I used BarcodeWriter from ZXing.Net.Bindings.SkiaSharp NuGet package.
using ZXing.SkiaSharp;
var barcodeWriter = new BarcodeWriter
{
Format = BarcodeFormat.QR_CODE,
Options = new EncodingOptions
{
Height = _height,
Width = _width,
Margin = _margin
}
};
using var bitmap = barcodeWriter.Write(qrValue);
using var stream = new MemoryStream();
bitmap.Encode(stream, SKEncodedImageFormat.Png, 100);
Your stream is filled now :)
I'm using WebApiContrib.Formatting.xlsx to create and download a Microsoft Excel file. My problem is that when called from the client the file can't be opened and several method were tried. When dealing with PDF the problem was resolved converting the output to Byte64 like this:
var response = new HttpResponseMessage
{
Content = new StringContent(Convert.ToBase64String(output.ToArray()))
};
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = "Report.pdf"
};
return response;
In the case of WebApiContrib.Formatting.xlsx I have an IEnumerable. How can convert it the same way as the PDF.
var subscriptionExcelModels = subscriptionPlansConverted as SubscriptionExcelModel[] ?? subscriptionPlansConverted.ToArray();
This is my snippet of the last part of the code for the excel file:
var ret = Request.CreateResponse(HttpStatusCode.OK,subscriptionExcelModels);
ret.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
ret.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = "Report.xlsx"
};
return ret;
i want to generate image for windows 8 app, i'm going to use SharpDX API
here is the code sample which i thankfully coped and paste
private MemoryStream RenderStaticTextToBitmap()
{
var width = 400;
var height = 100;
var pixelFormat = WicPixelFormat.Format32bppBGR;
var wicFactory = new ImagingFactory();
var dddFactory = new SharpDX.Direct2D1.Factory();
var dwFactory = new SharpDX.DirectWrite.Factory();
var wicBitmap = new Bitmap(
wicFactory,
width,
height,
pixelFormat,
BitmapCreateCacheOption.CacheOnLoad);
var renderTargetProperties = new RenderTargetProperties(
RenderTargetType.Default,
new D2DPixelFormat(Format.Unknown, AlphaMode.Unknown),
0,
0,
RenderTargetUsage.None,
FeatureLevel.Level_DEFAULT);
var renderTarget = new WicRenderTarget(
dddFactory,
wicBitmap,
renderTargetProperties)
{
TextAntialiasMode = TextAntialiasMode.Cleartype
};
renderTarget.BeginDraw();
var textFormat = new TextFormat(dwFactory, "Consolas", 48)
{
TextAlignment = SharpDX.DirectWrite.TextAlignment.Center,
ParagraphAlignment = ParagraphAlignment.Center
};
var textBrush = new SharpDX.Direct2D1.SolidColorBrush(
renderTarget,
SharpDX.Colors.Blue);
renderTarget.Clear(Colors.White);
renderTarget.DrawText(
"Hi, mom!",
textFormat,
new RectangleF(0, 0, width, height),
textBrush);
renderTarget.EndDraw();
var ms = new MemoryStream();
var stream = new WICStream(
wicFactory,
ms);
var encoder = new PngBitmapEncoder(wicFactory);
encoder.Initialize(stream);
var frameEncoder = new BitmapFrameEncode(encoder);
frameEncoder.Initialize();
frameEncoder.SetSize(width, height);
frameEncoder.PixelFormat = WicPixelFormat.FormatDontCare;
frameEncoder.WriteSource(wicBitmap);
frameEncoder.Commit();
encoder.Commit();
frameEncoder.Dispose();
encoder.Dispose();
stream.Dispose();
ms.Position = 0;
return ms;
}
this working in excellent way with installed fonts .... i have font in the assets folder and i want to use -i have about 604 custom fonts and i chose the font dynamically- , i know there is away to load file from folder .... help plz
Unfortunately, afaik, there is no API in DirectWrite that supports this easily. You need to develop your own font loader and related classes. There is the SharpDX sample CustomFont that is loading fonts from resources, so you could adapt it to load from another location.
I have to retrieve an image from the disk or a web link , resize it and stream it to the client app. This is my controller method.
[HttpPost]
[ActionName("GetImage")]
public HttpResponseMessage RetrieveImage(ImageDetails details)
{
if (!details.Filename.StartsWith("http"))
{
if (!FileProvider.Exists(details.Filename))
{
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound, "File not found"));
}
var filePath = FileProvider.GetFilePath(details.Filename);
details.Filename = filePath;
}
var image = ImageResizer.RetrieveResizedImage(details);
MemoryStream stream = new MemoryStream();
// Save image to stream.
image.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
var response = new HttpResponseMessage();
response.Content = new StreamContent(stream);
response.Content.Headers.ContentDisposition
= new ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentDisposition.FileName = details.Filename;
response.Content.Headers.ContentType
= new MediaTypeHeaderValue("application/octet-stream");
return response;
}
And this is how am sending the web link(in this case) and receiving the image at the client app end.
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:27066");
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/octet-stream"));
ImageDetails img = new ImageDetails { Filename = "http://2.bp.blogspot.com/-W6kMpFQ5pKU/TiUwJJc8iSI/AAAAAAAAAJ8/c3sJ7hL8SOw/s1600/2011-audi-q7-review-3.jpg", Height = 300, Width = 200 };
var response = await client.PostAsJsonAsync("api/Media/GetImage", img);
response.EnsureSuccessStatusCode(); // Throw on error code.
var stream = await response.Content.ReadAsStreamAsync();
FileStream fileStream = System.IO.File.Create("ImageName");
// Initialize the bytes array with the stream length and then fill it with data
byte[] bytesInStream = new byte[stream.Length];
stream.Read(bytesInStream, 0, (int)bytesInStream.Length);
// Use write method to write to the specified file
fileStream.Write(bytesInStream, 0, (int) bytesInStream.Length);
MessageBox.Show("Uploaded");
The image is being retrieved from the web link and the resizing is done properly but am not sure if its being streamed proeprly as its creating a 0kb file with "ImageName" when received at client app. Can anyone please tell me where am going wrong? I have been banging my head about it all day :(
Try resetting the position of the memory stream before passing it to the response:
stream.Position = 0;
response.Content = new StreamContent(stream);
I suppose that your image resizing library is leaving the position of the memory stream at the end.