I am trying to encode a particular string into a QR Code. I have been used Zxing lib for this.I am not able to generate the qr code using this piece of code. I have tried using Bitmap but windows 8 doesn't allow System.drawing assembly...
public ZXing.Rendering.PixelData get()
{
string url="abcdefghijkl";
BarcodeWriter _writer = new BarcodeWriter();
_writer.Format = BarcodeFormat.QR_CODE;
_writer.Options.Height = 400;
_writer.Options.Width = 400;
_writer.Options.Margin = 1;
var barcodeImage = _writer.Write("tel:" + url); //tel: prefix for phone numbers
return barcodeImage;
}
You have to use the correct pre-built assembly for your target platform.
There is a binary for WinRT available which doesn't use the Bitmap class.
https://zxingnet.codeplex.com/releases
If you use the version for Windows Metadata (WinMD) you have to convert the
raw bytes of the PixelData to an image. It depends on the application you write
and the things you want to do.
There are sample client projects for nearly every platform available
which show you how to use the library.
Related
I need to take a ticket id (only digits, but as a string), turn the string into a 1D barcode, then convert that to a image or bitmap or svg, then convert that into a base64 encoded string, where the base64 string can be returned as a response in a endpoint. It has be done in .NET6 and I'm doing it on a Mac (MacOS)
This is what I have so far (just put it in a console app for testing purposes):
using System.Drawing;
using BarcodeLib;
byte[] ImageToByteArray(Image image)
{
MemoryStream ms = new MemoryStream();
image.Save(ms,image.RawFormat);
return ms.ToArray();
}
var ticketId = "038000356216";
Barcode b = new Barcode();
Image img = b.Encode(TYPE.UPCA, ticketId, Color.Black, Color.White, 290, 120);
var barcodeAsString = Convert.ToBase64String(ImageToByteArray(img));
Console.WriteLine(barcodeAsString);
This does work because the Barcodelib uses Windows specific API's, which then causes a exception on the Mac. This code would properly work on a Windows machine. But since I'm on a Mac this is the the issue that I would like your help with.
How can I do this in a "platform neutral" way - something that will work on both MacOS and Windows?
I'm open for using any open source library/Nuget package that supports this - just as long as I don't have to pay for it, or there is going to be a waterwark on the image.
I have tried several libraries / Nuget packages - all with the same result as in the example.
I want to convert an Embedded image to base 64 string. The image is in PCL solution so let me know how to convert an image into base64. As I tried lots of ways but I am not getting the file path properly. So please help me with this.
//file to base64 string
byte[] b = System.IO.File.ReadAllBytes(FileName);
String s = Convert.ToBase64String(b);
//base64 string to file
byte[] data = Convert.FromBase64String(s);
System.IO.File.WriteAllBytes(FileName2, data);
Since it is an embedded resource getting the path for the image is a problem to convert it into a stream, you can take the following steps to get the path of your embedded image:
string imagePath = "NameOfProject.Assets.applicationIcon.png";
Note: This is the sample path in your case you will give your path, Where the name of the project is the name of the project, Assets is the folder in which I have the image and application icon is the image. (I hope you understood what I am doing here)
After that get the Assembly details something like this:
Assembly assembly = typeof(NameOfClass).GetTypeInfo().Assembly;
Then inside a using statement convert your image into a stream, Something like this
string result;
using (Stream stream = assembly.GetManifestResourceStream(imagePath))
{
long length = stream.Length;
byte[] buffer = new byte[length];
stream.Read(buffer, 0, (int)length);
result = Convert.ToBase64String(data);
}
Revert in case of queries.
I'm trying to download a PNG image in Apps Script, convert it to JPEG, and generate a data URI for this new JPEG.
function test() {
var blob = UrlFetchApp.fetch('https://what-if.xkcd.com/imgs/a/156/setup.png').getBlob();
var jpeg = blob.getAs("image/jpeg");
var uri = 'data:image/jpeg;base64,' + Utilities.base64Encode(jpeg.getBytes());
Logger.log(uri);
}
When I run this, I get:
The image you are trying to use is invalid or corrupt.
Even something like:
function test() {
var bytes = UrlFetchApp.fetch('https://what-if.xkcd.com/imgs/a/156/setup.png').getBlob().getBytes();
var jpeg = Utilities.newBlob(bytes, MimeType.PNG).getAs(MimeType.JPEG);
DriveApp.createFile(jpeg);
}
doesn't work.
Your code is correct. This may be a bug, but it's specific to the file you are using, so may as well be a bug in the file (i.e., the file could indeed be corrupted somehow). Or maybe it uses some features of PNG format that Google doesn't handle. Replacing the URL by another one, e.g.,
var blob = UrlFetchApp.fetch('https://cdn.sstatic.net/Sites/mathematica/img/logo#2.png').getBlob();
both functions work as expected.
SSRS report in VS2015 using a custom function to convert a value to barcode image using zxing.dll. I found this article Generate barcode using Visual Studio local report or SSRS which is essentially identical to what I'm trying to do and have followed it. When I preview the report, it produces the warnings below and the image shows the red-x. I can deploy the report but no images appear in the related columns. The image is set with the correct mime type (image/bmp) but I've tried others with the same results.
NOTE: I've searched for and read several articles that helped me make progress but can't seem to resolve this issue.
The complete errors are:
[rsRuntimeErrorInExpression] The Value expression for the image ‘ImageFromFunction’ contains an error: Request for the permission of type 'System.Security.Permissions.SecurityPermission, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.
[rsInvalidDatabaseImageProperty] The value of the ImageData property for the image ‘ImageFromFunction’ is “=Code.TextToBarcode128Bmp(Fields!barcode_value.Value)”, which is not a valid ImageData.
I have a WPF where this same code (in C#) works fine. There is just something about using it in SSRS that it doesn't like. The first message seems to indicate that it is a permissions/version kind of thing. I know that SSRS is .NET 2.0. I've set my reference to System.Drawing to 2.0 versions and copied over the 2.0 version of zxing.dll to the server.
It looks like it is attempting to get security permissions (probably for the zxing.dll?) but is unable to reach System.Security.Permissions.SecurityPermission?
References
zxing, Version=0.15.0.0, Culture=neutral, PublicKeyToken=4e88037ac681fe60
System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
I tried added a reference to the 2.0 version of System.Security but it still produced the same error.
This is the custom function:
Public Function TextToBarcode(ByVal text As String) As Byte()
Dim writer As New ZXing.BarcodeWriter()
writer.Format = ZXing.BarcodeFormat.CODE_128
writer.Options = New ZXing.Common.EncodingOptions
writer.Options.Width = 125
writer.Options.Height = 100
Dim bmp As System.Drawing.Bitmap = writer.Write(text)
Dim ms AS System.IO.MemoryStream = new System.IO.MemoryStream()
bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp)
Dim imagedata as byte()
imagedata = ms.GetBuffer()
Return imagedata
End Function
UPDATE
I followed the steps in the article SSRS: System.Security.Permissions.SecurityPermission (Thanks, Michael and Superman) which is based upon this article How to use custom assemblies or embedded code in Reporting Services
On the server, I added zxing.dll to the GAC from its location in D:\Program Files\Microsoft SQL Server\MSRS12.MSSQLSERVER\Reporting Services\ReportServer\bin
On the server, I added a CodeGroup to D:\Program Files\Microsoft SQL Server\MSRS12.MSSQLSERVER\Reporting Services\ReportServer\rssrvpolicy.config:
<CodeGroup
class="UnionCodeGroup"
version="1"
PermissionSetName="FullTrust"
Name="ZXingCodeGroup"
Description="Code group for ZXing">
<IMembershipCondition
class="UrlMembershipCondition"
version="1"
Url="D:\Program Files\Microsoft SQL Server\MSRS12.MSSQLSERVER\Reporting Services\ReportServer\bin\zxing.dll"
/>
</CodeGroup>
And I restarted Reporting Services. No change in behavior: Running deployed report produces no errors but does not display the barcode.
On the VS dev system, I then added the CodeGroup to C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\PrivateAssemblies\RSPreviewPolicy.config and closed and re-opened Visual Studio. No change in behavior: Preview of report shows same warnings and fails to display the barcode.
UPDATE
I've confirmed this is some kind of permissions issue. By commenting the line that does the ZXing.BarcoderWriter.Write() call it no longer produces this error. In fact, by replacing the function body with code that populates a byte array from image data (below), it successfully displays the image:
Public Function getBarCodeHorizontal(ByVal text1 As String) As Byte()
Dim text as String = "89504E470D0A1A0A0000000D494844520000009600000028080200000093A394B0000000017352474200AECE1CE90000000467414D410000B18F0BFC6105000000097048597300000EC300000EC301C76FA8640000026549444154785EED9AB16EDB400C864F7D112BC892C10F5103196474CD1B548F20C32FE1B1A3FC065D8B6A28203F84072F46EC2751792475C79364C0E822B1E0372824EF3FDAB93FC7C041B2AEEBDC145996C1135621204D0888C934EC0A155CE46E04C9C293AB424F6229A3546A085A22821EE24701E9A942C84AD00C0461952AC0584FABB2EE758894510ACF81009EA1422910768DB748BEF057432D66A17ACC42F59885EA310BD56316AAC72C548F59A81EB3503D66A17ACC42F59885EA310BD56316AAC72C548F59A81EB3503D66A17ACC42F59885EA310BD56316AAC72C544FF21F8F8646EC16AAC72C54CFFF61E169976D8F774EFE9DFB719BED4E9CA8C16EA17ACC42F52CCA4298878C188B7EBA31E9B00CEAEDF1CA254FD0F3484C87ACC8E2AB0D1AA7133599AEC3E64B603916C2E96CCEF50D3EE4745DBB2E733C2428E6E5BAC5E2AD765C05E0FC378EEADDFE521EA8EAEBACBFD5E70D8ABF7EAB9A9F7FD8A2D3AF43F1F1BEF2D16E73A8A8415B35E58F672C19375F04F84D2C805B5D383ED2C8A018D3B67205DB0DF83AA5A21EC5107131DDD61394E32089279BCFCF626EE1E7A529DE5E3879C0EA75EDCE57B850F7EB994B88AF079A32C75197970D89DDEAFDC3E13D8C7710E9A7A2573EC9B8F9FC2CC6C297B7A2B97C72F200EFDCFA152C483C1B20AFD9EFEFE8177B080E567BAAA07DF9658F2A7FA59E64A2F9FCF0FB991F7F90724E618CA7DB4F2C186449DCAB7DDC275123D5BE0F20669F588DDBFDAB0D37CB77F0A0F9CC2CC742000F9388E7836748F49E11415DD4B5F81D27CA429DFC2C7862DBAAED17FD57D684656C1E364E379F17FB33B77AECA3BD7ACC42E538F7178726B2F89D7D5EF80000000049454E44AE426082"
Dim bytes As Byte() = New Byte(text.Length \ 2 - 1) {}
Dim b as Byte
For i As Integer = 0 To text.Length - 1 Step 2
bytes(i \ 2) = Byte.Parse(text(i).ToString() & text(i + 1).ToString(), System.Globalization.NumberStyles.HexNumber)
Next
Return bytes
End Function
UPDATE
I tried changing the CodeGroup on the server to Strong using the zxing.dll public key token, but no improvement:
<CodeGroup
class="UnionCodeGroup"
version="1"
PermissionSetName="FullTrust"
Name="ZXingCodeGroup"
Description="Code group for ZXing">
<IMembershipCondition
class="StrongNameMembershipCondition"
version="1"
PublicKeyBlob="4e88037ac681fe60"
/>
</CodeGroup>
Ohh that's a good one..
Did a lot of digging and debugging (if you can call that debugging - I put return statements into the ZXing code, and watched when it would bring up that error)
One thing that is different in my setup than yours: I am using a custom DLL to interact with zxing.dll.
It boils down to the way they put pixel-data into a bitmap:
https://github.com/micjahn/ZXing.Net/blob/eef88ee53ced1035eade39f44544aa955d2db6b6/Source/lib/renderer/BitmapRenderer.cs#L169
The Workaround is to convert it manually:
public static string Test()
// Don't let ZXing handle the conversion to a bitmap -> give me raw pixel data
var writer = new BarcodeWriterPixelData { Format = BarcodeFormat.DATA_MATRIX };
var result = writer.Write("Test123");
Bitmap bmp = new Bitmap(result.Width, result.Height);
int bpp = 32;
for (int y = 0; y < result.Height; y++)
{
for (int x = 0; x < result.Width; x++)
{
int i = ((y * result.Width) + x) * (bpp / 8);
if (bpp == 32) // in this case you have 4 color values (red, green, blue,alpha)
{
// first byte will be red, because you are writing it as first value
byte r = result.Pixels[i];
byte g = result.Pixels[i + 1];
byte b = result.Pixels[i + 2];
byte a = result.Pixels[i + 3]; // Alpha?
Color color = Color.FromArgb(r, g, b);
bmp.SetPixel(x, y, color);
}
}
}
return GetBase64(bmp);
}
public static string GetBase64(Image image)
{
using (MemoryStream m = new MemoryStream())
{
image.Save(m, ImageFormat.Png);
byte[] imageBytes = m.ToArray();
return Convert.ToBase64String(imageBytes);
}
}
Source (slightly modified):
https://stackoverflow.com/a/16130425/11829240
Also be aware, that you maybe need to build it yourself to insert [assembly:AllowPartiallyTrustedCallers] into AssemblyInfo.cs
The perfect solution would be to generate a SVG, but SSRS doesn't like that.
More to read on that Bitmap.LockBits Topic:
https://www.codeproject.com/Articles/625868/LockBits-Alternative-SecurityException-Workaround
Also found the following:
Hi,
I'm trying to create a Barcode in CRM 2011 (On Premises) Reports. Unfortunately this isn't possible due to Sandbox and various other issues. I've tried a few methods but nothing works.
So my approach now, is to create a c# plugin that generates the barcode image when a record is created, and store the image byte as a string, and then use Convert.FromBase64String in the report to display the barcode image. This method should then hopefully work...
However, after days of trying, I'm stuck with an issue with Permission Security
System.Security.SecurityException: Request for the permission of type 'System.Security.Permissions.SecurityPermission, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.
, and have debugged to a section in the Render that doesn't work / compatible (for CRM 2011..!)
var bmpData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb);
So my question is: Is there a way to do this without Lockbits ?
Any help here would be greatly received.
Unfortunately the Links is dead:
http://zxingnet.codeplex.com/discussions/584679
EDIT: Actually dug it up, Archive of an Archive..
https://web.archive.org/web/20210303162237/https://archive.codeplex.com/?p=zxingnet
Click on discussions and Search for Alternative to LockBits due to Security issues
Codeplex-Archive-Download (zip):
https://web.archive.org/web/20210701004220/https://codeplexarchive.blob.core.windows.net/archive/projects/ZXingNet/ZXingNet.zip
I use different tools like processing to create vector plots. These plots are written as single or multi-page pdfs. I would like to include these plots in a single report-like pdf using pdfbox.
My current workflow includes these pdfs as images with the following pseudo code
PDDocument inFile = PDDocument.load(file);
PDPage firstPage = (PDPage) inFile.getDocumentCatalog().getAllPages().get(0);
BufferedImage image = firstPage.convertToImage(BufferedImage.TYPE_INT_RGB, 300);
PDXObjectImage ximage = new PDPixelMap(document, image);
PDPageContentStream contentStream = new PDPageContentStream(document, page);
contentStream.drawXObject(ximage, 0, 0, ximage.getWidth(), ximage.getHeight());
contentStream.close();
While this works it looses the benefits of the vector file formats, espectially file/size vs. printing qualitity.
Is it possible to use pdfbox to include other pdf pages as embedded objects within a page (Not added as a separate page)? Could I e.g. use a PDStream? I would prefer a solution like pdflatex is able to embed pdf figures into a new pdf document.
What other Java libraries can you recommend for that task?
Is it possible to use pdfbox to include other pdf pages as embedded objects within a page
It should be possible. The PDF format allows the use of so called form xobjects to serve as such embedded objects. I don't see an explicit implementation for that, though, but the procedure is similar enough to what PageExtractor or PDFMergerUtility do.
A proof of concept derived from PageExtractor using the current SNAPSHOT of the PDFBox 2.0.0 development version:
PDDocument source = PDDocument.loadNonSeq(SOURCE, null);
List<PDPage> pages = source.getDocumentCatalog().getAllPages();
PDDocument target = new PDDocument();
PDPage page = new PDPage();
PDRectangle cropBox = page.findCropBox();
page.setResources(new PDResources());
target.addPage(page);
PDFormXObject xobject = importAsXObject(target, pages.get(0));
page.getResources().addXObject(xobject, "X");
PDPageContentStream content = new PDPageContentStream(target, page);
AffineTransform transform = new AffineTransform(0, 0.5, -0.5, 0, cropBox.getWidth(), 0);
content.drawXObject(xobject, transform);
transform = new AffineTransform(0.5, 0.5, -0.5, 0.5, 0.5 * cropBox.getWidth(), 0.2 * cropBox.getHeight());
content.drawXObject(xobject, transform);
content.close();
target.save(TARGET);
target.close();
source.close();
This code imports the first page of a source document to a target document as XObject and puts it twice onto a page there with different scaling and rotation transformations, e.g. for this source
it creates this
The helper method importAsXObject actually doing the import is defined like this:
PDFormXObject importAsXObject(PDDocument target, PDPage page) throws IOException
{
final PDStream src = page.getContents();
if (src != null)
{
final PDFormXObject xobject = new PDFormXObject(target);
OutputStream os = xobject.getPDStream().createOutputStream();
InputStream is = src.createInputStream();
try
{
IOUtils.copy(is, os);
}
finally
{
IOUtils.closeQuietly(is);
IOUtils.closeQuietly(os);
}
xobject.setResources(page.findResources());
xobject.setBBox(page.findCropBox());
return xobject;
}
return null;
}
As mentioned above this is only a proof of concept, corner cases have not yet been taken into account.
To update this question:
There is already a helper class in org.apache.pdfbox.multipdf.LayerUtility to do the import.
Example to show superimposing a PDF page onto another PDF: SuperimposePage.
This class is part of the Apache PDFBox Examples and sample transformations as shown by #mkl were added to it.
As mkl appropriately suggested, PDFClown is among the Java libraries which provide explicit support for page embedding (so-called Form XObjects (see PDF Reference 1.7, § 4.9)).
In order to let you get a taste of the way PDFClown works, the following code represents the equivalent of mkl's PDFBox solution (NOTE: as mkl later stated, his code sample was by no means optimised, so this comparison may not correspond to the actual status of PDFBox -- comments are welcome to clarify this):
Document source = new File(SOURCE).getDocument();
Pages sourcePages = source.getPages();
Document target = new File().getDocument();
Page targetPage = new Page(target);
target.getPages().add(targetPage);
XObject xobject = sourcePages.get(0).toXObject(target);
PrimitiveComposer composer = new PrimitiveComposer(targetPage);
Dimension2D targetSize = targetPage.getSize();
Dimension2D sourceSize = xobject.getSize();
composer.showXObject(xobject, new Point2D.Double(targetSize.getWidth() * .5, targetSize.getHeight() * .35), new Dimension(sourceSize.getWidth() * .6, sourceSize.getHeight() * .6), XAlignmentEnum.Center, YAlignmentEnum.Middle, 45);
composer.showXObject(xobject, new Point2D.Double(targetSize.getWidth() * .35, targetSize.getHeight()), new Dimension(sourceSize.getWidth() * .4, sourceSize.getHeight() * .4), XAlignmentEnum.Left, YAlignmentEnum.Top, 90);
composer.flush();
target.getFile().save(TARGET, SerializationModeEnum.Standard);
source.getFile().close();
Comparing this code to PDFBox's equivalent you can notice some relevant differences which show PDFClown's neater style (it would be nice if some PDFBox expert could validate my assertions):
Page-to-FormXObject conversion: PDFClown natively supports a dedicated method (Page.toXObject()), so there's no need for additional heavy-lifting such as the helper method importAsXObject();
Resource management: PDFClown automatically (and transparently) allocates page resources, so there's no need for explicit calls such as page.getResources().addXObject(xobject, "X");
XObject drawing: PDFClown supports both high-level (explicit scale, translation and rotation anchors) and low-level (affine transformations) methods to place your FormXObject into the page, so there's no need to necessarily deal with affine transformations.
The whole point is that PDFClown features a rich architecture made up of multiple abstraction layers: according to your requirements, you can choose the most appropriate coding style (either to delve into PDF's low-level basic structures or to leverage its convenient and elegant high-level model). PDFClown lets you tweak every single byte and solve complex tasks with a ridiculously simple method call, at your will.
DISCLOSURE: I'm the lead developer of PDFClown.