I started searching how to create a Windows Phone 8 app to recognize barcodes inside a PDF document.
My best guest is to following the process below:
Find a lib to split PDF documents into image streams (one per page).
Find a lib to recognize if there is a barcode in the image stream:
2.1. Try to recognize barcode in each portion of the image, i. e.:
try #1 (from y = 0, x = 0 to y = 100, x = 100);
try #2 (from y = 100, x = 0 to y = 200, x = 100);
try #3 (from y = 200, x = 0 to y = 300, x = 100);
and so on.
I'm wondering if this is the best approach to accomplish barcode recognition in a PDF document using WP8.
Another concern is about whether this process when executed by a not so good device will present an acceptable performance.
Someone already did that? Any advice?
UPDATE
I want to scan ITF barcodes, i. e., I need to scan the barcode in this image:
I'm trying to start achieving the scanning barcodes from a Image, but I'm not getting success. Below is my first try:
//get the assets folder for the app
StorageFolder folder = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFolderAsync("Assets");
BitmapSource bitmapSource = await GetBitmapImage(folder, "Barcode.png");
WriteableBitmap writeableBitmap = new WriteableBitmap(bitmapSource);
var rgb = new RGBLuminanceSource(writeableBitmap.ToByteArray(), writeableBitmap.PixelWidth, writeableBitmap.PixelHeight);
var hybrid = new HybridBinarizer(rgb);
BinaryBitmap binBitmap = new BinaryBitmap(hybrid);
Reader reader = new ITFReader();
try
{
Result result = reader.decode(binBitmap);
if (result != null)
{
this.textBlock.Text = result.Text;
}
}
catch (Exception ex)
{
this.textBlock.Text = ex.Message;
}
Unfortunately, my text box is being filled up with this Exception:
Exception of type 'com.google.zxing.ReaderException' was thrown.
I'm using this "lib": https://silverlightzxing.codeplex.com/
Yes, this concept actually works.
Read the PDF as Image
after that use any external Library to detect Barcodes from image. (There are many libraries available to do so)
And for another concern that you mentioned regarding performance of Low-End devices, it depends on many things.
First of all it depends on the library that you use to convert PDF to Image
then library that you use to detect Barcode from Image.
though there is no certainity for Time Complexity in this Task, what i think is it will not take much time then required..! It's a general process, so you can go with the scenario above.
Hope that helps...
I'd like to help you to implement the part 1 of the solution, render PDF to image:
this blog post shows how to do it on windows phone and this lib can be used to convert PDFs to images in universal windows store apps as well as xamarin apps. I personally use it in my projects and because it offers same API for all platforms it fits incredibly well.
Related
It's my first time resizing images in ASP.NET Core, so after a bit of research I found this approach to be the easiest and most efficient and I implemented it as shown below.
However, I am not sure if that approach is the most efficient one since there are two issues with it that go as follows
Images lose a lot of their quality
I get this 'warning' in Visual Studio that is fine as long as I am the only one who develops it, however that will not always be the case if someone else does -
This call site is reachable on all platforms. 'Bitmap' is only supported on windows.
Therefore I wonder what are other approaches more decent that exist and I can implement to at least fix the first of both issues.
public async Task<IActionResult> Add(AddCardFormModel card, List<IFormFile> ImageFile)
{
// ...
foreach (var image in ImageFile)
{
if (image.Length > 0 || image.Length <= (2 * 1024 * 1024))
{
var imagesToBeResized = Image.FromStream(image.OpenReadStream());
var resized = new Bitmap(imagesToBeResized, new Size(250, 350));
using (var stream = new MemoryStream())
{
resized.Save(stream, ImageFormat.Jpeg);
var cardData = new Card
{
Title = card.Title,
Description = card.Description,
ImageUrl = card.ImageUrl,
CategoryId = card.CategoryId,
ConditionId = card.ConditionId,
Price = card.Price,
DealerId = dealerId,
Image = stream.ToArray()
};
this.data.Cards.Add(cardData);
this.data.SaveChanges();
}
}
}
// ...
}
The System.Drawing.Common package is only supported on Windows.
If you want your application to work cross-platform then Microsoft suggests to migrate to one of the following libraries:
ImageSharp
SkiaSharp
Microsoft.Maui.Graphics
https://learn.microsoft.com/en-us/dotnet/core/compatibility/core-libraries/6.0/system-drawing-common-windows-only#recommended-action
You should first decide which image processing library you will use in your project and after that look for the best algorithm for resizing images using that specific library.
Check this library for image resizing.
but I suggest don't store images on the database, because the database size and log size will be increased.
you have 2 options:
Option 1: store resized images on directories and save names in the database.
Option 2: store the original size on directories and resize it in real-time.
I've been attempting to find an easy solution to exporting a Canvas in my WPF Application to a PDF Document.
So far, the best solution has been to use the PrintDialog and set it up to automatically use the Microsoft Print the PDF 'printer'. The only problem I have had with this is that although the PrintDialog is skipped, there is a FileDialog to choose where the file should be saved.
Sadly, this is a deal-breaker because I would like to run this over a large number of canvases with automatically generated PDF names (well, programitically provided anyway).
Other solutions I have looked at include:
Using PrintDocument, but from my experimentation I would have to manually iterate through all my Canveses children and manually invoke the correct Draw method (of which a lot of my custom elements with transformation would be rather time consuming to do)
Exporting as a PNG image and then embedding that in a PDF. Although this works, TextBlocks within my canvas are no longer text. So this isn't an ideal situation.
Using the 3rd party library PDFSharp has the same downfall as the PrintDocument. A lot of custom logic for each element.
With PDFSharp. I did find a method fir generating the XGraphics from a Canvas but no way of then consuming that object to make a PDF Page
So does anybody know how I can skip or automate the PDF PrintDialog, or consume PDFSharp XGraphics to make
A page. Or any other ideas for directions to take this besides writing a whole library to convert each of my Canvas elements to PDF elements.
If you look at the output port of a recent windows installation of Microsoft Print To PDF
You may note it is set to PORTPROMP: and that is exactly what causes the request for a filename.
You might note lower down, I have several ports set to a filename, and the fourth one down is called "My Print to PDF"
So very last century methodology; when I print with a duplicate printer but give it a different name I can use different page ratios etc., without altering the built in standard one. The output for a file will naturally be built:-
A) Exactly in one repeatable location, that I can file monitor and rename it, based on the source calling the print sequence, such that if it is my current default printer I can right click files to print to a known \folder\file.pdf
B) The same port can be used via certain /pt (printto) command combinations to output, not just to that default port location, but to a given folder\name such as
"%ProgramFiles%\Windows NT\Accessories\WORDPAD.EXE" /pt listIN.doc "My Print to PDF" "My Print to PDF" "listOUT.pdf"
Other drivers usually charge for the convenience of WPF programmable renaming, but I will leave you that PrintVisual challenge for another of your three wishes.
MS suggest XPS is best But then they would be promoting it as a PDF competitor.
It does not need to be Doc[X]2PDF it could be [O]XPS2PDF or aPNG2PDF or many pages TIFF2PDF etc. etc. Any of those are Native to Win 10 also other 3rd party apps such as [Free]Office with a PrintTo verb will do XLS[X]2PDF. Imagination becomes pagination.
I had a great success in generating PDFs using PDFSharp in combination with SkiaSharp (for more advanced graphics).
Let me begin from the very end:
you save the PdfDocument object in the following way:
PdfDocument yourDocument = ...;
string filename = #"your\file\path\document.pdf"
yourDocument.Save(filename);
creating the PdfDocument with a page can be achieved the following way (adjust the parameters to fit your needs):
PdfDocument yourDocument = new PdfDocument();
yourDocument.PageLayout = PdfPageLayout.SinglePage;
yourDocument.Info.Title = "Your document title";
PdfPage yourPage = yourDocument.AddPage();
yourDocument.Orientation = PageOrientation.Landscape;
yourDocument.Size = PageSize.A4;
the PdfPage object's content (as an example I'm putting a string and an image) is filled in the following way:
using (XGraphics gfx = XGraphics.FromPdfPage(yourPage))
{
XFont yourFont = new XFont("Helvetica", 20, XFontStyle.Bold);
gfx.DrawString(
"Your string in the page",
yourFont,
XBrushes.Black,
new XRect(0, XUnit.FromMillimeter(10), page.Width, yourFont.GetHeight()),
XStringFormats.Center);
using (Stream s = new FileStream(#"path\to\your\image.png", FileMode.Open))
{
XImage image = XImage.FromStream(s);
var imageRect = new XRect()
{
Location = new XPoint() { X = XUnit.FromMillimeter(42), Y = XUnit.FromMillimeter(42) },
Size = new XSize() { Width = XUnit.FromMillimeter(42), Height = XUnit.FromMillimeter(42.0 * image.PixelHeight / image.PixelWidth) }
};
gfx.DrawImage(image, imageRect);
}
}
Of course, the font objects can be created as static members of your class.
And this is, in short to answer your question, how you consume the XGraphics object to create a PDF page.
Let me know if you need more assistance.
I need to show the preview thumbnails of high resolution images in a control for user selection. I currently use ImageListView to load images.
This works fine for low to medium resolution images.But when it comes to showing thumbnails of very high resolution images there is a noticeable delay.Sample image can be downloaded from https://drive.google.com/open?id=1Qgu_aVXBiMlbHluJFU4fBvmFC45-E81C
The image size is around 5000x3000 pixels and size is around 12 MB.The issue can be replicated by using 1000 copies of this image.
The issue screen capture is uploaded here
https://giphy.com/gifs/ZEH3T3JTfN42OL3J1A
The images are loaded using a background worker
foreach (var f in filepaths)
{
imageListView1.Items.Add(f);
}
1. In order to solve this issue I tried resizing large resolution images and adding the resized image to ImageListView ... but for resizing there is a heavy time consumption and thumbnail generation is slow.
Bitmap x = UpdatedResizeImage2(new Bitmap(f), new Size(1000, 1000));
string q = Path.GetTempPath() + Path.GetFileName(f);
x.Save(Path.GetTempPath() + Path.GetFileName(f));
x.Dispose();
imageListView1.Items.Add(Path.GetTempPath() + Path.GetFileName(f));
2. I have also tried Image.CreateThumbnail Method but this is also quite slow.
Is there a better way to solve this issue?
I would suggest using image processing library such ImageMagick.
ImageMagick has optimized this feature and you have Magick.NET a nuget package for .NET.
It is simple and straight forward:
var file = new FileInfo(#"c:\temp\input.jpg");
using (MagickImage image = new MagickImage(file))
{
{
image.Thumbnail(new MagickGeometry(100, 100));
image.Write(#"C:\temp\thumbnail.jpg");
}
}
example I made:
Here is some documentation and references that might be useful:
https://imagemagick.org/Usage/thumbnails/#creation
http://www.imagemagick.org/Usage/thumbnails/
https://github.com/dlemstra/Magick.NET
https://www.smashingmagazine.com/2015/06/efficient-image-resizing-with-imagemagick/
https://devblogs.microsoft.com/dotnet/net-core-image-processing/
https://weblogs.asp.net/bleroy/resizing-images-from-the-server-using-wpf-wic-instead-of-gdi
Alternatives to System.Drawing for use with ASP.NET?
You could use WPF interop and use the DecodePixelWidth/Height properties. They use underlying Windows imaging layer technology ("Windows Imaging Component") to create an optimized thumbnail, saving lots of memory (and possibly CPU): How to: Use a BitmapImage (XAML)
You can also use WPF/WIC by code, with a code like this (adapted from this article The fastest way to resize images from ASP.NET. And it’s (more) supported-ish.. You just need to add a reference to PresentationCore and WindowsBase which shouldn't be an issue for a desktop app.
// needs System.Windows.Media & System.Windows.Media.Imaging (PresentationCore & WindowsBase)
public static void SaveThumbnail(string absoluteFilePath, int thumbnailSize)
{
if (absoluteFilePath == null)
throw new ArgumentNullException(absoluteFilePath);
var bitmap = BitmapDecoder.Create(new Uri(absoluteFilePath), BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.None).Frames[0];
int width;
int height;
if (bitmap.Width > bitmap.Height)
{
width = thumbnailSize;
height = (int)(bitmap.Height * thumbnailSize / bitmap.Width);
}
else
{
width = (int)(bitmap.Width * thumbnailSize / bitmap.Height);
height = thumbnailSize;
}
var resized = BitmapFrame.Create(new TransformedBitmap(bitmap, new ScaleTransform(width / bitmap.Width * 96 / bitmap.DpiX, height / bitmap.Height * 96 / bitmap.DpiY, 0, 0)));
var encoder = new PngBitmapEncoder();
encoder.Frames.Add(resized);
var thumbnailFilePath = Path.ChangeExtension(absoluteFilePath, thumbnailSize + Path.GetExtension(absoluteFilePath));
using (var stream = File.OpenWrite(thumbnailFilePath))
{
encoder.Save(stream);
}
}
Otherwise there are lots of tools out there like MagicScaler, FreeImage ImageSharp, ImageMagick, Imazen, etc. Most were written for ASP.NET/Web server scenarios (for which WPF is officially not supported but works, read the article) and are also cross-platform which you don't seem to need. I'm not sure they're generally faster or use less memory than builtin Windows technology, but you should test all this in your context.
PS: otherwise there's no magic bullet, bigger images take more time.
There's also NetVips, the C# binding for libvips.
It's quite a bit quicker than Magick.NET: between 3x and 10x faster, depending on the benchmark.
Thumbnailing is straightforward:
using NetVips;
var image = Image.Thumbnail("some-image.jpg", 128);
image.WriteToFile("x.jpg");
There's an introduction in the documentation.
Most of answers approach is to resize bitmap and then save it. Its a bit offcourse slow, specially if you say very high resolution.
Why not use existing thumbnail created by windows explorer ? This is fastest way of all (specially if you use smaller thumbnails).
//https://stackoverflow.com/a/1751610
using Microsoft.WindowsAPICodePack.Shell;
var shellFile = ShellFile.FromFilePath(pathToYourFile); Bitmap
Image image = shellFile.Thumbnail.LargeBitmap;
Nuget : https://www.nuget.org/packages/WindowsAPICodePack-Shell (around 600KB)
Note: Its same as others, if thumbnail arent cached already.
I have written a windows store app in XAML & C# to read image from tablet's webcam and decode the barcode using Zxing's lbrary. The code is working fine on a given tablet having an i5 processor while it fails to run on an actual tablet with 2MP camera and "Intel Baytrail Quad-Core" processor.
Any ideas on why this could happen?
Please let me know if you need to see my code for this issue ad I will share.
I am wondering how can the same code work on 1 tablet while fail on another tablet.
Thanks in advance for any help provided.
EDIT
Code used to scan the barcode and read as below - The last if/else block is what I get to. No exception raised :(
string barcodeData = string.Empty;
using (var imageStream = new InMemoryRandomAccessStream())
{
processingImage = true;
var encodingProperties = new ImageEncodingProperties();
encodingProperties.Subtype = "Jpeg";
encodingProperties.Width = 400;
encodingProperties.Height = 400;
await captureMgr.CapturePhotoToStreamAsync(encodingProperties, imageStream);
await imageStream.FlushAsync();
imageStream.Seek(0);
var bitmap = new WriteableBitmap(400, 400);
bitmap.SetSource(imageStream);
preview1.Source = bitmap; //preview1 is an Image control to display the captured image
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.SetSource(imageStream);
imageStream.Seek(0);
var bitmapDecoder = await BitmapDecoder.CreateAsync(BitmapDecoder.JpegDecoderId, imageStream);
var data = await bitmapDecoder.GetPixelDataAsync(
BitmapPixelFormat.Bgra8,
BitmapAlphaMode.Straight,
new BitmapTransform(),
ExifOrientationMode.IgnoreExifOrientation,
ColorManagementMode.DoNotColorManage
);
if (data != null)
{
BarcodeReader barcodeReader = new BarcodeReader();
var result = barcodeReader.Decode(
data.DetachPixelData(),
(int)bitmapDecoder.PixelWidth,
(int)bitmapDecoder.PixelHeight,
ZXing.RGBLuminanceSource.BitmapFormat.BGR32
);
if (result != null)
{
//Barcode found
}
else
//No data found.
}
}
I guess you are using ZXing.NET library.
Have you ever considered moving to another barcode scanner library?
Accessing the "ISSUES" section in ZXing.NET Library, you can see that there's a lot of bugs still opened for Windows Phone (and should be Window Store also).
http://zxingnet.codeplex.com/workitem/list/basic
One of it called my attention. Check out this comment:
While the WP samples all target Silverlight, you must not forget that the new WP8.1 base is WinRT - so I suggest you use the WinRT sample as a base.
I tried to do the same, but truth to be told, ZXing lacks a lot ATM for WinRT Universal Apps - it's slow, unreliable, and barely ever recognizes a thing.
http://zxingnet.codeplex.com/workitem/13311
I don't know how reliable this is, but the last time the project was updated was on April 7th!!!!
You should really consider changing you library!
Hi,
I made a lib for WinRT using ZXing & Imaging SDK.
It works well (but does not include any additional focus feature).
https://github.com/stepheUp/VideoScanZXing4WP81
There is a lib and a sample app that you can try.
It works for barcodes and QRCode (barcode by default but just change the optional parameter in the scan function code to use QRCode)
Hope it helps,
Stéphanie
I need to implement Instagram photo effects like amaro, hudson, sepia, rise, and so on. I know this article only use basic effects: http://code.msdn.microsoft.com/windowsdesktop/Metro-Style-lightweight-24589f50
Another way suggested by people are to implement Direct2d and then apply using that. But for that I would need to write C++ code, where I have zero experience.
Can anyone suggest some other way to implement Instagram effects in c#?
Is there any built in c++ file for these effects?
Please see this example from CodeProject : Metro Style Lightweight Image Processing
The above example contains these image effects.
Negative
Color filter
Emboss
SunLight
Black & White
Brightness
Oilpaint
Tint
Please note above example seems to be implemented on either developer preview or release preview of Windows 8. So you will get error like this
'Windows.UI.Xaml.Media.Imaging.WriteableBitmap' does not contain a
constructor that takes 1 arguments
So you have to create instance of WriteableBitmap by passing pixel height and pixel width of image. I have edited the sample and it is working for me. You have to change wb = new WriteableBitmap(bs); to wb = await GetWB();
StorageFile originalImageFile;
WriteableBitmap cropBmp;
public async Task<WriteableBitmap> GetWB()
{
if (originalImageFile != null)
{
//originalImageFile is the image either loaded from file or captured image.
using (IRandomAccessStream stream = await originalImageFile.OpenReadAsync())
{
BitmapImage bmp = new BitmapImage();
bmp.SetSource(stream);
BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream);
byte[] pixels = await GetPixelData(decoder, Convert.ToUInt32(bmp.PixelWidth), Convert.ToUInt32(bmp.PixelHeight));
cropBmp = new WriteableBitmap(bmp.PixelWidth, bmp.PixelHeight);
Stream pixStream = cropBmp.PixelBuffer.AsStream();
pixStream.Write(pixels, 0, (int)(bmp.PixelWidth * bmp.PixelHeight * 4));
}
}
return cropBmp;
}
Let me know if you are facing any problem.