Bing Maps CustomMapTileDataSource wont load pixelData - c#

I am writing a UWP application using the MapControl I have implemented my own MapTileSource like so:
var nativeTileLayer = new MapTileSource();
nativeTileLayer.DataSource = new UWPSyncTileLayer();
nativeTileLayer.TilePixelSize = outerItem.TileSize;
nativeTileLayer.AllowOverstretch = true;
// NativeMap.Style = MapStyle.None;
outerItem.NativeObject = nativeTileLayer;
NativeMap.TileSources.Clear();
NativeMap.TileSources.Add(nativeTileLayer);
return nativeTileLayer;
Where UWPSyncTileLayer is my own implementation of CustomMapTileDataSource
internal class UWPSyncTileLayer : CustomMapTileDataSource
{
public UWPSyncTileLayer(int tileSize = 256)
{
this.BitmapRequested += UWPSyncTileLayer_BitmapRequested;
}
private void UWPSyncTileLayer_BitmapRequested(CustomMapTileDataSource sender, MapTileBitmapRequestedEventArgs args)
{
var deferral = args.Request.GetDeferral();
var data = Convert.FromBase64String("iVBORw0KGgoAAAANSUhEUgAAAQAAAAEACAYAAABccqhmAAASQUlEQVR42u3dfZBeVX3A8W921+263W7jNk1pmomZqJmYiTHS8GKIaUSLNFIa0SJSYZRBy5Si0lZbHOgMwx8MoxQp06LT0oigtKLgtIIKyjvyJuHFQCCEgCRACHlZlnWTbLKb/nHOSoBN2Ow+z73n3Pv9zJxJhpnwPM+5v/O755x77jmTkPLSGct0YDZwUPzvPwUetXqkamkD5gGnACuAh4CXgD2vKXdaVeOrXCk1HcB84M+BY4FZQNcb/JvpVpuUr5bYpf8y8MAod/g3KuutQinPhr8AuBrYNo6GbwKQMh1+LgauBXZNoOGbAKTM7vhLgOuA7Q1o+CPlSatWStuceMcfamDDHykPWb1SmtqBzwHPN6Hhj5SbrWYpve7+4cA9TWz4I+Uqq/vAuQ5AzbzrnwecBnQX8HmbrXITgNIwE7gMOLLAz3zWapfKtwh4ooAu/2vLcqteKrc3eRqjr9NvdhkivC8gqQSdwMU05/HeWMqLvPJWoKQCdQBXlNj49xCeMnR4KaTi7/yXldjwR8qlXgqp+Dv/5SXf+UfG/yd6OaR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wxyCdwph26xbgV2J3PUvAQ4yrHUgOmIgP1HCGPVFwtOJo8h3Br4tJtILYh0WnQy2Az8DFnnX10TvaGfT/PcIdsa75mcJLy9VSTdh3cW3af7OzbsIO/gchZvBqIF6gNMIs+47G3Sn3xYb/ZfihFp7xeuwJdbjCbGHs75BdbkzjvEviL0OG/4oXAfQuKHBIuDD8S4z5wACboDw/Plu4E7CTjPralyX3cACwlqMQ2Ljnc4bT3L2E06IfjTO1ayMZcDwNAEUqTMG7FzCJN1oG0cOE46SepqwTdlWDmxRTl20xPrrJEzYTYsJonOvRt8X63JTrMMBPCJ+zP4fl44XyBRTFr4AAAAASUVORK5CYII=".Split(",".ToCharArray(), 2)[1]);
MemoryStream stream = new MemoryStream();
stream.Write(data, 0, data.Length);
stream.Position = 0;
var decoder = Windows.Graphics.Imaging.BitmapDecoder.CreateAsync(stream.AsRandomAccessStream()).AsTask().Result;
var pixelProvider = decoder.GetPixelDataAsync().AsTask().Result;// Windows.Graphics.Imaging.BitmapPixelFormat.Rgba8, Windows.Graphics.Imaging.BitmapAlphaMode.Ignore, new Windows.Graphics.Imaging.BitmapTransform(), Windows.Graphics.Imaging.ExifOrientationMode.RespectExifOrientation, Windows.Graphics.Imaging.ColorManagementMode.ColorManageToSRgb).AsTask().Result;
var pixelData = pixelProvider.DetachPixelData();
InMemoryRandomAccessStream randomAccessStream = new InMemoryRandomAccessStream();
IOutputStream outputStream = randomAccessStream.GetOutputStreamAt(0);
DataWriter writer = new DataWriter(outputStream);
writer.WriteBytes(pixelData);
var i = writer.StoreAsync().AsTask().Result;
var d = writer.FlushAsync().AsTask().Result;
args.Request.PixelData = RandomAccessStreamReference.CreateFromStream(randomAccessStream);
deferral.Complete();
}
}
But the image is always blank.
Does anyone know what I'm doing wrong?

I can't tell from your data stream, but it looks like you might be passing a compressed PNG stream to the PixelData property. You'll need to decode a PNG to RGB values and set PixelData to the decoded RGBA buffer. See the example code here:https://msdn.microsoft.com/en-us/library/windows/apps/windows.ui.xaml.controls.maps.maptilebitmaprequest.pixeldata.aspx

Related

Unable to read QR using Zxing

I am using zxing library to generate and decode the QR codes. I my application I am generating QR code dynamically and sending the file containing QR by fax API. If I get this fax message from the api and decode it, Qr code is read successfully, but when I send a scanned copy of this file by fax and then receive and read it I am unable to do that. But if I try to read this file using my mobile Qr application it properly reads the Qr code. I am unable to find a solution how to read this file.
Methods used for encoding:
public static System.Drawing.Image GenerateJSONQrCode(QRJsonFax model)
{
var jsonString = JsonConvert.SerializeObject(model);
//encrypt json string
jsonString = Hugo.BLL.Utilities.EncryptionHelper.EncryptQR(jsonString, FaxSetting.IsUseHashing);
var bw = new ZXing.BarcodeWriter();
var encOptions = new ZXing.Common.EncodingOptions() { Width = 200, Height = 200, Margin = 0 };
bw.Options = encOptions;
bw.Format = ZXing.BarcodeFormat.QR_CODE;
var image = new Bitmap(bw.Write(Compress(jsonString)));
return image;
}
private static string Compress(string text)
{
byte[] buffer = Encoding.UTF8.GetBytes(text);
var ms = new MemoryStream();
using (var zip = new GZipStream(ms, CompressionMode.Compress, true))
{
zip.Write(buffer, 0, buffer.Length);
}
ms.Position = 0;
byte[] compressed = new byte[ms.Length];
ms.Read(compressed, 0, compressed.Length);
byte[] gzBuffer = new byte[compressed.Length + 4];
System.Buffer.BlockCopy(compressed, 0, gzBuffer, 4, compressed.Length);
System.Buffer.BlockCopy(BitConverter.GetBytes(buffer.Length), 0, gzBuffer, 0, 4);
return Convert.ToBase64String(gzBuffer);
}
Methods used for encoding and decoding
public static FaxReceiver.QrFinder DecodeQrCode(string imagePathToDecode)
{
long userId = 0;
Bitmap bitmapImage = (Bitmap)Image.FromFile(imagePathToDecode);
ZXing.BarcodeReader barcodeReader = new BarcodeReader() { AutoRotate = true, TryHarder = true }; ;
Result decode = barcodeReader.Decode(bitmapImage);
var scanResult = string.Empty;
if (decode != null)
{
scanResult= Decompress(decode.Text);
}
if (!string.IsNullOrWhiteSpace(scanResult))
{
//decrypt Qr received
var decryptedString = DecryptionHelper.Decrypt(scanResult, FaxSetting.IsUseHashing);
//deserialize JSON received
var resultJson = JsonConvert.DeserializeObject<QRJsonFax>(decryptedString);
if (resultJson != null)
{
long.TryParse(resultJson.UserID.ToString(), out userId);
return new QrFinder()
{
FilePath = imagePathToDecode,
UserId = userId,
PageNo = 0,
DataSourceID = resultJson.DataSourceID,
InboundFaxTypeID = resultJson.InboundFaxTypeID
};
}
}
return null;
}
private static string Decompress(string compressedText)
{
byte[] gzBuffer = Convert.FromBase64String(compressedText);
using (var ms = new MemoryStream())
{
int msgLength = BitConverter.ToInt32(gzBuffer, 0);
ms.Write(gzBuffer, 4, gzBuffer.Length - 4);
byte[] buffer = new byte[msgLength];
ms.Position = 0;
using (var zip = new GZipStream(ms, CompressionMode.Decompress))
{
zip.Read(buffer, 0, buffer.Length);
}
return Encoding.UTF8.GetString(buffer);
}
}
File containing Qr code
The problem is that the QR Decoder is getting confused by the gaps between the pixels in your faxed image. If we zoom into a corner of it, this is what we see.
The scanner is looking for solid black squares to identify the QR code.
If we shrink the image by 50%, it becomes readable.
See for yourself at http://zxing.org/w/decode?u=http%3A%2F%2Fi.stack.imgur.com%2FSCYsd.png
I would suggest that after receiving the faxed image, you should either shrink it, or apply a filter to ensure that the QR codes are solid black. You could also look at sending it at a smaller resolution to see if that helps.

Decode QR code from Byte[] using ZXing in C#

I can decode QR code from an image file as follows-
Bitmap bitmap = new Bitmap(imagePath);
BarcodeReader reader = new BarcodeReader();
Result result = reader.Decode(bitmap);
decodedData = result.Text;
But I want it to do from Byte[].
Byte[] imagefile;
using (var binaryReader = new BinaryReader(Request.Files["files"].InputStream))
{
imagefile = binaryReader.ReadBytes(Request.Files["files"].ContentLength);//image
}
I would like to read QR code from this imagefile variable. Is there any way to do it?
Thank you.
How about:
using (var binaryReader = new BinaryReader(Request.Files["files"].InputStream))
{
byte[] imagefile = binaryReader.ReadBytes(Request.Files["files"].ContentLength); //image
using (MemoryStream memory = new MemoryStream(imagefile))
using (Image bitmap = Image.FromStream(memory)
{
BarcodeReader reader = new BarcodeReader();
Result result = reader.Decode(bitmap);
decodedData = result.Text;
}
}
Or may be even shorter:
using (Image bitmap = Image.FromStream(Request.Files["files"].InputStream))
{
BarcodeReader reader = new BarcodeReader();
Result result = reader.Decode(bitmap);
decodedData = result.Text;
}

getting images from web link and converting it into base64string in a loop

i need to convert the images(fetching from web service) into base64String to store them in the SQLite database.
EDIT: I use ImageOpened so that the image is loaded/downloaded before I convert them into base64String but ImageOpened doest run. How do I achieve this task ? I mean to convert array of images into base64.
this is my code:
public async void LoadData()
{
//get Json
string str = await Helper.getJSON();
//Deserialize json
MainClass apiData = JsonConvert.DeserializeObject<MainClass>(str);
//the problem loop
for (int i = 0; i < apiData.Categories.Count;i++ )
{
//apiData.Categoriesp[i].icon_image is the url of the image
BitmapImage image = new BitmapImage(new Uri(apiData.Categories[i].icon_image,UriKind.RelativeOrAbsolute));
//it never runs
image.ImageOpened += (s, e) =>
{
//code for conversion of image into memory stream
image.CreateOptions = BitmapCreateOptions.None;
WriteableBitmap wb = new WriteableBitmap(image);
MemoryStream ms = new MemoryStream();
wb.SaveJpeg(ms, image.PixelWidth, image.PixelHeight, 0, 100);
byte[] imageBytes = ms.ToArray();
string base64String = Convert.ToBase64String(imageBytes);
//setting imageInSql property of the list (but it never runs)
apiData.Categories[i].imageInSql = base64String;
};
}
//Inserting into database
using(var db= new SQLiteConnection(App.dbPath)){
//geting null in imageinSql property.
db.InsertAll(apiData.Categories,typeof(Category));
}
}
Thanks in advance.
For me it looks like a you are setting CreateOptions property inside the event handler.
image.ImageOpened += (s, e) =>
{
//code for conversion of image into memory stream
image.CreateOptions = BitmapCreateOptions.None;
You should do this like-
image.CreateOptions = BitmapCreateOptions.None;
image.ImageOpened += (s, e) =>
{
Try below code.
public async void LoadData()
{
//get Json
string str = await Helper.getJSON();
//Deserialize json
MainClass apiData = JsonConvert.DeserializeObject<MainClass>(str);
//the problem loop
for (int i = 0; i < apiData.Categories.Count;i++ )
{
//apiData.Categoriesp[i].icon_image is the url of the image
BitmapImage image = new BitmapImage(new Uri(apiData.Categories[i].icon_image,UriKind.RelativeOrAbsolute));
image.CreateOptions = BitmapCreateOptions.None
//it never runs
image.ImageOpened += (s, e) =>
{
//code for conversion of image into memory stream
WriteableBitmap wb = new WriteableBitmap(image);
MemoryStream ms = new MemoryStream();
wb.SaveJpeg(ms, image.PixelWidth, image.PixelHeight, 0, 100);
byte[] imageBytes = ms.ToArray();
string base64String = Convert.ToBase64String(imageBytes);
//setting imageInSql property of the list (but it never runs)
apiData.Categories[i].imageInSql = base64String;
};
}
//Inserting into database
using(var db= new SQLiteConnection(App.dbPath)){
//geting null in imageinSql property.
db.InsertAll(apiData.Categories,typeof(Category));
}
}

OpenPGP encryption with BouncyCastle

I have been trying to put together an in-memory public-key encryption infrastructure using OpenPGP via Bouncy Castle. One of our vendors uses OpenPGP public key encryption to encrypt all their feeds, and requires us to do the same, so I'm stuck with the technology and the implementation. So now I'm coding an OpenPGP encryption/ decryption toolkit for automating these feeds.
The examples at bouncycastle.org inexplicably default to writing encrypted data to and collecting keys from a file system; this is not what I want to do, so I've been trying to get everything stream-based.
I have gotten to the point where I can actually get my code to compile and run, but my encrypted payload is empty. I think I'm missing something silly, but after several days of trying this and that, I have lost the ability to objectively examine this.
My utility class contains these methods:
public static PgpPublicKey ImportPublicKey(
this Stream publicIn)
{
var pubRings =
new PgpPublicKeyRingBundle(PgpUtilities.GetDecoderStream(publicIn)).GetKeyRings().OfType<PgpPublicKeyRing>();
var pubKeys = pubRings.SelectMany(x => x.GetPublicKeys().OfType<PgpPublicKey>());
var pubKey = pubKeys.FirstOrDefault();
return pubKey;
}
public static Stream Streamify(this string theString, Encoding encoding = null)
{
encoding = encoding ?? Encoding.UTF8;
var stream = new MemoryStream(encoding.GetBytes(theString));
return stream;
}
public static string Stringify(this Stream theStream,
Encoding encoding = null)
{
encoding = encoding ?? Encoding.UTF8;
using (var reader = new StreamReader(theStream, encoding))
{
return reader.ReadToEnd();
}
}
public static byte[] ReadFully(this Stream stream)
{
if (!stream.CanRead) throw new ArgumentException("This is not a readable stream.");
var buffer = new byte[32768];
using (var ms = new MemoryStream())
{
while (true)
{
var read = stream.Read(buffer, 0, buffer.Length);
if (read <= 0)
return ms.ToArray();
ms.Write(buffer, 0, read);
}
}
}
public static void PgpEncrypt(
this Stream toEncrypt,
Stream outStream,
PgpPublicKey encryptionKey,
bool armor = true,
bool verify = true,
CompressionAlgorithmTag compressionAlgorithm = CompressionAlgorithmTag.Zip)
{
if (armor) outStream = new ArmoredOutputStream(outStream);
var compressor = new PgpCompressedDataGenerator(CompressionAlgorithmTag.Zip);
outStream = compressor.Open(outStream);
var data = toEncrypt.ReadFully();
var encryptor = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Cast5, verify, new SecureRandom());
encryptor.AddMethod(encryptionKey);
outStream = encryptor.Open(outStream, data.Length);
outStream.Write(data, 0, data.Length);
}
My test method looks like this:
private static void EncryptMessage()
{
var pubKey = #"<public key text>";
var clearText = "This is an encrypted message. There are many like it but this one is cryptic.";
using (var stream = pubKey.Streamify())
{
var key = stream.ImportPublicKey();
using (var clearStream = clearText.Streamify())
using (var cryptoStream = new MemoryStream())
{
clearStream.PgpEncrypt(cryptoStream,key);
cryptoStream.Position = 0;
Console.WriteLine(cryptoStream.Stringify());
Console.WriteLine("Press any key to continue.");
}
}
Console.ReadKey();
}
The result I get looks like this:
-----BEGIN PGP MESSAGE-----
Version: BCPG C# v1.7.4114.6378
Press any key to continue.
Can someone tell me what I am doing wrong?
OK, I managed to get this working. There were several problems with this implementation. One problem was that certain things had to be done in order. Here is what seems to need to happen:
The raw data needs to be put into a PgpLiteralData object
The literal data needs to be encrypted.
The encrypted data needs to be compressed.
The compressed data (optionally) needs to be armored.
The underlying streams need to be closed in order of usage.
There should be a more elegant way to do this, but the streams used by the BouncyCastle library are all frustratingly one-way, and at several points, I needed to convert the stream to a byte array to get another part to work. I include the code I used and independently verified; if someone has a verifyably better way of doing this, I would be quite interested.
public static class OpenPgpUtility
{
public static void ExportKeyPair(
Stream secretOut,
Stream publicOut,
AsymmetricKeyParameter publicKey,
AsymmetricKeyParameter privateKey,
string identity,
char[] passPhrase,
bool armor)
{
if (armor)
{
secretOut = new ArmoredOutputStream(secretOut);
}
var secretKey = new PgpSecretKey(
PgpSignature.DefaultCertification,
PublicKeyAlgorithmTag.RsaGeneral,
publicKey,
privateKey,
DateTime.UtcNow,
identity,
SymmetricKeyAlgorithmTag.Cast5,
passPhrase,
null,
null,
new SecureRandom()
);
secretKey.Encode(secretOut);
if (armor)
{
secretOut.Close();
publicOut = new ArmoredOutputStream(publicOut);
}
var key = secretKey.PublicKey;
key.Encode(publicOut);
if (armor)
{
publicOut.Close();
}
}
public static PgpPublicKey ImportPublicKey(
this Stream publicIn)
{
var pubRings =
new PgpPublicKeyRingBundle(PgpUtilities.GetDecoderStream(publicIn)).GetKeyRings().OfType<PgpPublicKeyRing>();
var pubKeys = pubRings.SelectMany(x => x.GetPublicKeys().OfType<PgpPublicKey>());
var pubKey = pubKeys.FirstOrDefault();
return pubKey;
}
public static PgpSecretKey ImportSecretKey(
this Stream secretIn)
{
var secRings =
new PgpSecretKeyRingBundle(PgpUtilities.GetDecoderStream(secretIn)).GetKeyRings().OfType<PgpSecretKeyRing>();
var secKeys = secRings.SelectMany(x => x.GetSecretKeys().OfType<PgpSecretKey>());
var secKey = secKeys.FirstOrDefault();
return secKey;
}
public static Stream Streamify(this string theString, Encoding encoding = null)
{
encoding = encoding ?? Encoding.UTF8;
var stream = new MemoryStream(encoding.GetBytes(theString));
return stream;
}
public static string Stringify(this Stream theStream,
Encoding encoding = null)
{
encoding = encoding ?? Encoding.UTF8;
using (var reader = new StreamReader(theStream, encoding))
{
return reader.ReadToEnd();
}
}
public static byte[] ReadFully(this Stream stream, int position = 0)
{
if (!stream.CanRead) throw new ArgumentException("This is not a readable stream.");
if (stream.CanSeek) stream.Position = 0;
var buffer = new byte[32768];
using (var ms = new MemoryStream())
{
while (true)
{
var read = stream.Read(buffer, 0, buffer.Length);
if (read <= 0)
return ms.ToArray();
ms.Write(buffer, 0, read);
}
}
}
public static void PgpEncrypt(
this Stream toEncrypt,
Stream outStream,
PgpPublicKey encryptionKey,
bool armor = true,
bool verify = false,
CompressionAlgorithmTag compressionAlgorithm = CompressionAlgorithmTag.Zip)
{
var encryptor = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Cast5, verify, new SecureRandom());
var literalizer = new PgpLiteralDataGenerator();
var compressor = new PgpCompressedDataGenerator(compressionAlgorithm);
encryptor.AddMethod(encryptionKey);
//it would be nice if these streams were read/write, and supported seeking. Since they are not,
//we need to shunt the data to a read/write stream so that we can control the flow of data as
//we go.
using (var stream = new MemoryStream()) // this is the read/write stream
using (var armoredStream = armor ? new ArmoredOutputStream(stream) : stream as Stream)
using (var compressedStream = compressor.Open(armoredStream))
{
//data is encrypted first, then compressed, but because of the one-way nature of these streams,
//other "interim" streams are required. The raw data is encapsulated in a "Literal" PGP object.
var rawData = toEncrypt.ReadFully();
var buffer = new byte[1024];
using (var literalOut = new MemoryStream())
using (var literalStream = literalizer.Open(literalOut, 'b', "STREAM", DateTime.UtcNow, buffer))
{
literalStream.Write(rawData, 0, rawData.Length);
literalStream.Close();
var literalData = literalOut.ReadFully();
//The literal data object is then encrypted, which flows into the compressing stream and
//(optionally) into the ASCII armoring stream.
using (var encryptedStream = encryptor.Open(compressedStream, literalData.Length))
{
encryptedStream.Write(literalData, 0, literalData.Length);
encryptedStream.Close();
compressedStream.Close();
armoredStream.Close();
//the stream processes are now complete, and our read/write stream is now populated with
//encrypted data. Convert the stream to a byte array and write to the out stream.
stream.Position = 0;
var data = stream.ReadFully();
outStream.Write(data, 0, data.Length);
}
}
}
}
}
My test method looked like this:
private static void EncryptMessage()
{
var pubKey = #"<public key text here>";
var clearText = #"<message text here>";
using (var stream = pubKey.Streamify())
{
var key = stream.ImportPublicKey();
using (var clearStream = clearText.Streamify())
using (var cryptoStream = new MemoryStream())
{
clearStream.PgpEncrypt(cryptoStream, key);
cryptoStream.Position = 0;
var cryptoString = cryptoStream.Stringify();
Console.WriteLine(cryptoString);
Console.WriteLine("Press any key to continue.");
}
}
Console.ReadKey();
}
Since someone asked, my decryption algorithm looked like this:
public static Stream PgpDecrypt(
this Stream encryptedData,
string armoredPrivateKey,
string privateKeyPassword,
Encoding armorEncoding = null)
{
armorEncoding = armorEncoding ?? Encoding.UTF8;
var stream = PgpUtilities.GetDecoderStream(encryptedData);
var layeredStreams = new List<Stream> { stream }; //this is to clean up/ dispose of any layered streams.
var dataObjectFactory = new PgpObjectFactory(stream);
var dataObject = dataObjectFactory.NextPgpObject();
Dictionary<long, PgpSecretKey> secretKeys;
using (var privateKeyStream = armoredPrivateKey.Streamify(armorEncoding))
{
var secRings =
new PgpSecretKeyRingBundle(PgpUtilities.GetDecoderStream(privateKeyStream)).GetKeyRings()
.OfType<PgpSecretKeyRing>();
var pgpSecretKeyRings = secRings as PgpSecretKeyRing[] ?? secRings.ToArray();
if (!pgpSecretKeyRings.Any()) throw new ArgumentException("No secret keys found.");
secretKeys = pgpSecretKeyRings.SelectMany(x => x.GetSecretKeys().OfType<PgpSecretKey>())
.ToDictionary(key => key.KeyId, value => value);
}
while (!(dataObject is PgpLiteralData) && dataObject != null)
{
try
{
var compressedData = dataObject as PgpCompressedData;
var listedData = dataObject as PgpEncryptedDataList;
//strip away the compression stream
if (compressedData != null)
{
stream = compressedData.GetDataStream();
layeredStreams.Add(stream);
dataObjectFactory = new PgpObjectFactory(stream);
}
//strip the PgpEncryptedDataList
if (listedData != null)
{
var encryptedDataList = listedData.GetEncryptedDataObjects()
.OfType<PgpPublicKeyEncryptedData>().First();
var decryptionKey = secretKeys[encryptedDataList.KeyId]
.ExtractPrivateKey(privateKeyPassword.ToCharArray());
stream = encryptedDataList.GetDataStream(decryptionKey);
layeredStreams.Add(stream);
dataObjectFactory = new PgpObjectFactory(stream);
}
dataObject = dataObjectFactory.NextPgpObject();
}
catch (Exception ex)
{
//Log exception here.
throw new PgpException("Failed to strip encapsulating streams.", ex);
}
}
foreach (var layeredStream in layeredStreams)
{
layeredStream.Close();
layeredStream.Dispose();
}
if (dataObject == null) return null;
var literalData = (PgpLiteralData)dataObject;
var ms = new MemoryStream();
using (var clearData = literalData.GetInputStream())
{
Streams.PipeAll(clearData, ms);
}
ms.Position = 0;
return ms;
}

ZXing.Net Encode string to QR Code in CF

How could I encode my string into a QR Code using ZXing.Net?
I can already decode, but having problems in encoding. It has an error that says: no encoder available for format AZTEC.
Here is my code:
IBarcodeWriter writer = new BarcodeWriter();
Bitmap barcodeBitmap;
var result = writer.Encode("Hello").ToBitmap();
barcodeBitmap = new Bitmap(result);
pictureBox1.Image = barcodeBitmap;
You don't fully initialize the BarcodeWriter. You have to set the barcode format.
Try the following code snippet:
IBarcodeWriter writer = new BarcodeWriter { Format = BarcodeFormat.QR_CODE };
var result = writer.Write("Hello");
var barcodeBitmap = new Bitmap(result);
pictureBox1.Image = barcodeBitmap;
#dizzytri99er
Seems that I have sucessfully encoded a message with ZXing.net therefore I think it does support Aztec encoding
This is the code I have used;
static void Main(string[] args)
{
IBarcodeWriter writer = new BarcodeWriter
{
Format = BarcodeFormat.AZTEC
};
Bitmap aztecBitmap;
var result = writer.Write("I love you ;)");
aztecBitmap = new Bitmap(result);
using (var stream = new FileStream("test.bmp", FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
var aztecAsBytes = ImageToByte(aztecBitmap);
stream.Write(aztecAsBytes, 0, aztecAsBytes.Length);
}
}
public static byte[] ImageToByte(Image img)
{
ImageConverter converter = new ImageConverter();
return (byte[])converter.ConvertTo(img, typeof(byte[]));
}
could it possibly be the size of the codes your are scanning?
take a look here
best way to generate and encode QR codes would be...
QR code encoder and Zbar

Categories

Resources