.net barcode generation - c#

I am developing a barcode generating web application using asp.net/c# ,I was wondering if it is better to use barcode library or a barcode font will be just enough.I have come across some samples but when using barcode font I found there is an asterisk(*) in front of the each code used for generating barcode.And I dint find any free barcode libraries. I want to generate code 39 or 93. Please help me decide

try jquery-barcode
Its a javascript library to generate bar codes. Check out this question for other alternatives.

Here is an extension method I am using that doesn't require you to install the font:
public static Image GetBarCode(this string data, int fontSizeEm)
{
data = "*" + data + "*";
Image img = null;
Graphics drawing = null;
try
{
using (var pfc = new PrivateFontCollection())
{
pfc.AddFontFile(#"{{PATH TO YOUR FONT FILE}}");
using (var myfont = new Font(pfc.Families[0], fontSizeEm))
{
img = new Bitmap(1, 1);
drawing = Graphics.FromImage(img);
var textSize = drawing.MeasureString(data, myfont);
img.Dispose();
drawing.Dispose();
img = new Bitmap((int) textSize.Width, (int) textSize.Height);
drawing = Graphics.FromImage(img);
drawing.DrawString(data, myfont, new SolidBrush(Color.Black), 0, 0);
}
drawing.Save();
}
return img;
}
catch
{
//Handle exception
return null;
}
finally
{
if(drawing!= null)
drawing.Dispose();
}
}

In my experience, libraries that generate barcodes via graphic primitives like rectangles are far superior to barcode fonts. Reasons:
Fonts are much larger, often orders of magnitude, and take much longer to transmit. This is especially problematic on serial connections.
The barcodes fonts produce are often less accurate as printers may try to anti-alias the bars.
Fonts are subject to things like styles, word-wrapping, font substitution, and other effects that make them difficult to control.
There are plenty of free barcode image libraries. If you didn't find any you did not look very well.
Barcode 3 of 9 requires guard bars at the start and end of the code so the scanner knows where the code starts and ends. When printing the legend for a code 3 of 9, these guard bars are traditionally shown as asterisks. These asterisks are only for humans reading the legend, they are not part of the code and in fact an asterisk is not a legal code 3 of 9 character. If you remove the guard bars the scanner would not be able to read the barcode.

Related

Is there a way to place a vector drawing in the PrintPage-event of printDocument?

I am writing an application that creates "print" files for a laser engraver.
It is using specific RGB values for setting the laser speed and power (e.g. RGB(0,0,0) for setting 1, RGB(255,0,0) for setting 2). It will ignore any element where the RGB value is just a little bit off.
As we are printing nameplates with this device, I need as result a PDF file with many nameplates on it. I have coded a "nameplate designer" where you can design the nameplate (e.g. line in RGB(0,0,0) at x=10mm, y=10mm ....).
My initial thought was to code an interpreter which does return a Bitmap and place these bitmaps on the print file. It works, it looks good, BUT due to the pixel graphics, the colors are not 100% accurate at the edges.
should be all RGB(0,255,0)
It is 100% accurate when I put the interpreter in the PrintPage-event of printDocument, but I would like to maintain the possibility to export the image as Bitmap when needed (e.g. a customer asks for a preview). Now could I just copy the interpreter (1 for Bitmap, 1 for PrintPage), but for maintainability it would be better to have this code just once for both output ways.
I tried with Metafile, but don't know how to place it in the PrintPage-event properly (page is just blank currently) // or how to create the Metafile properly
private Metafile printMF()
{
Graphics grfx = CreateGraphics();
MemoryStream ms = new MemoryStream();
IntPtr ipHdc = grfx.GetHdc();
Metafile mf = new Metafile(ms, ipHdc);
grfx.ReleaseHdc(ipHdc);
grfx.Dispose();
grfx = Graphics.FromImage(mf);
grfx.DrawLine(new Pen(Brushes.Black), 10, 10, 300, 10);
grfx.DrawRectangle(new Pen(Brushes.Black), new Rectangle(20, 20, 400, 400));
return mf;
}
private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
Metafile mf = printMF();
e.Graphics.DrawImage(mf, 20, 20,500,500);
}
Is there any obvious mistake or is it just impossible and I have to create two interpreters.
Thanks a lot for your help!

imagesharp trying to make an animated gif that count from 0 to 9

anyone could tell me why this generate a black only animated gif?
the code also output each in memory generated gif to show that they are different
public static void Test()
{
Image<Rgba32> img = null;
Image<Rgba32> gif = null;
TextGraphicsOptions textGraphicsOptions = new TextGraphicsOptions(true);
SolidBrush<Rgba32> brushYellow = new SolidBrush<Rgba32>(Rgba32.Yellow);
FontCollection fonts = new FontCollection();
fonts.Install(fontLocation);
Font font = fonts.CreateFont("Liberation Mono", PngFontHeight, FontStyle.Regular);
gif = new Image<Rgba32>(400, 400);
for (int i = 0; i < 10;++i)
{
img = new Image<Rgba32>(400, 400);
img.Mutate(x => x.Fill(Rgba32.Black));
img.Mutate(x => x.DrawText(textGraphicsOptions, i.ToString(), font, brushYellow, new PointF(1,1)));
gif.Frames.AddFrame(img.Frames[0]);
using (FileStream fs = File.Create(Path.Join(Program.workingDirectory, string.Format("Test-{0}.gif", i))))
{
img.SaveAsGif(fs);
}
img.Dispose();
}
using (FileStream fs = File.Create(Path.Join(Program.workingDirectory, "Test.gif")))
{
gif.SaveAsGif(fs);
}
}
if I code it to load each individual physical file using this code it make the animated gif as expected.
I want to create the animated gif in memory only.
When you create an Image<>...
gif = new Image<Rgba32>(400, 400);
...gif.Frames[0] is a "transparent black" frame (each pixel's RGBA value is #00000000). The additional frames you create in your for loop and add with...
gif.Frames.AddFrame(img.Frames[0]);
...become gif.Frames[1] through gif.Frames[10], for a total of 11 frames.
The GIF encoder uses GifColorTableMode to decide if a color table is generated for each frame or the color table for the first frame is used for all frames. The combination of the default value, GifColorTableMode.Global, plus that first transparent frame results in an 11-frame .gif file with only one color, that same "transparent black". This is why your yellow text doesn't appear and every frame looks the same.
To solve this, at some point before you save the file you need to remove that initial transparent frame so it doesn't influence color table calculations and because it's not part of your animation, anyways...
gif.Frames.RemoveFrame(0);
You may also want to change to GifColorTableMode.Local so your .gif file contains color tables reflecting all of the colors rendered...
gif.MetaData.GetFormatMetaData(GifFormat.Instance).ColorTableMode = GifColorTableMode.Local;
...although your 10 frames each use almost the same set of colors so if file size is a greater concern than color representation you might leave that property alone. Generating your 400 × 400 animation with GifColorTableMode.Global produces a 9,835-byte file whereas GifColorTableMode.Local produces a 16,703-byte file; 70% bigger but I can't tell the difference between them.
Related issue on GitHub
By the way, since I found this along the way, if you wanted to change the duration of the animated frames you would do so using another GetFormatMetaData() method similar to the one shown above...
GifFrameMetaData frameMetaData = img.MetaData.GetFormatMetaData(GifFormat.Instance);
frameMetaData.FrameDelay = 100;// 1 second

Picturebox from AForge FFMPEG empty - C#/WinForms

I've done a ton of research and looked at a lot of questions here but can't seem to find anything to help me. I should preface I'm very new to C#, Windows Forms, and SO! I'm a 1st year CompSci student coming from C++ experimenting with my own projects for the summer. I'm trying to display a series of bitmaps from a .avi using the AForge.Video.FFMPEG video file reader.
It seems to be finding the file, getting its' data (console prints dimensions, framerate, and codec) and creating the picturebox, but the picturebox comes up blank/empty. I get the bitmap from the frames of a .avi:
From AForge example code here
Then I'm trying to display it with a picture box:
From MS example code here as well
And here's my code. Essentially a combination of the two:
public class Simple : Form
{
Bitmap videoFrame;
public Simple()
{
try
{
// create instance of video reader
VideoFileReader reader = new VideoFileReader();
// open video file
reader.Open(#"C:\Users\User\Desktop\ScanTest3.AVI");
// check some of its attributes
Console.WriteLine("width: " + reader.Width);
Console.WriteLine("height: " + reader.Height);
Console.WriteLine("fps: " + reader.FrameRate);
Console.WriteLine("codec: " + reader.CodecName);
PictureBox pictureBox1 = new PictureBox();
// read 100 video frames out of it
for (int i = 0; i < 100; i++)
{
videoFrame = reader.ReadVideoFrame();
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
pictureBox1.ClientSize = new Size(videoFrame.Width, videoFrame.Height);
pictureBox1.Image = videoFrame;
// dispose the frame when it is no longer required
videoFrame.Dispose();
}
reader.Close();
}
catch
{
Console.WriteLine("Nope");
}
}
}
class MApplication
{
public static void Main()
{
Application.Run(new Simple());
}
}
So that's it pretty much. Just a blank picture box coming up, when it should have the first frame of the video, even though no exception caught (though I'm pretty confident I'm using the try/catch very poorly), and the console printing the correct data for the file:
width: 720
height: 480
fps: 29
codec: dvvideo
[swscaler # 05E10060] Warning: data is not aligned! This can lead to a speedloss
Though if anyone could tell me what that warning means, that would be great as well, but I'm mainly just lost as to why there's no picture printing to the screen.
Thanks!
Found This post, where he uses timers to update, and it works perfectly. I'm guessing pictureBox only really works in a function maybe, not sure. Still learning. Thanks!

Removing Text based watermarks using itextsharp

According to this post (Removing Watermark from PDF iTextSharp) , #mkl code works fine for ExGstate graphical watermarks but I have tested this code to remove watermark from some files which have Text based watermarks behind PDF contents (like this file : http://s000.tinyupload.com/index.php?file_id=05961025831018336372)
I have tried multiple solutions that found in this site but get no success.
Can anyone help to remove this watermark types by changing above #mkl solution?
thanks
Just like in the case of the question the OP references (Removing Watermark from PDF iTextSharp), you can remove the watermark from your sample file by building upon the PdfContentStreamEditor class presented in my answer to that question.
In contrast to the solution in that other answer, though, we do not want to hide vector graphics based on some transparency value but instead the writing "Archive of SID" from this:
First we have to select a criterion to recognize the background text by. Let's use the fact that the writing is by far the largest here. Using this criterion makes the task at hand essentially the iTextSharp/C# pendant to this iText/Java solution.
There is a problem, though: As mentioned in that answer:
The gs().getFontSize() used in the second sample may not be what you expect it to be as sometimes the coordinate system has been stretched by the current transformation matrix and the text matrix. The code can be extended to consider these effects.
Exactly this is happening here: A font size of 1 is used and that small text then is stretched by means of the text matrix:
/NxF0 1 Tf
49.516754 49.477234 -49.477234 49.516754 176.690933 217.316086 Tm
Thus, we need to take the text matrix into account. Unfortunately the text matrix is a private member. Thus, we will also need some reflection magic.
Thus, a possible background remover for that file looks like this:
class BigTextRemover : PdfContentStreamEditor
{
protected override void Write(PdfContentStreamProcessor processor, PdfLiteral operatorLit, List<PdfObject> operands)
{
if (TEXT_SHOWING_OPERATORS.Contains(operatorLit.ToString()))
{
Vector fontSizeVector = new Vector(0, Gs().FontSize, 0);
Matrix textMatrix = (Matrix) textMatrixField.GetValue(this);
Matrix curentTransformationMatrix = Gs().GetCtm();
Vector transformedVector = fontSizeVector.Cross(textMatrix).Cross(curentTransformationMatrix);
float transformedFontSize = transformedVector.Length;
if (transformedFontSize > 40)
return;
}
base.Write(processor, operatorLit, operands);
}
System.Reflection.FieldInfo textMatrixField = typeof(PdfContentStreamProcessor).GetField("textMatrix", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
List<string> TEXT_SHOWING_OPERATORS = new List<string>{"Tj", "'", "\"", "TJ"};
}
The 40 has been chosen with that text matrix in mind.
Applying it like this
[Test]
public void testRemoveBigText()
{
string source = #"sid-1.pdf";
string dest = #"sid-1-noBigText.pdf";
using (PdfReader pdfReader = new PdfReader(source))
using (PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileStream(dest, FileMode.Create, FileAccess.Write)))
{
PdfContentStreamEditor editor = new BigTextRemover();
for (int i = 1; i <= pdfReader.NumberOfPages; i++)
{
editor.EditPage(pdfStamper, i);
}
}
}
to your sample file results in:

Need some lite library/code that will create thumbnails and is optimal for use with ASP.NET MVC

Below is the action method that returns images from the database as they are, I need some lite library or write the code myself if short that will resize and compress these images according to my requirements "Make thumbnails" before they are passed to the HTTP response.
EDIT: Actually come to think of it, perhaps it would be best to save thumbnails in additional column, so now I need a way to compress and resize the images before they are saved to the database a long with saving a copy that is untouched. Saving images initially by passing them in HttpPostedFileBase and now need some tool that will resize and compress before saving to database.
public FileContentResult GetImage(int LineID)
{
var PMedia = repository.ProductMedias.FirstOrDefault(x => x.LineID == LineID);
if (PMedia != null)
{
return File(PMedia.ImageData, PMedia.ImageMimeType, PMedia.FileName);
}
else
{
return null;
}
}
Is your thumbnail size different everytime? Otherwise it is probably optimal to have another Column/Storage with Resized photos for your Thumbnails than processing them every time.
System.Drawing can be used to create thumbnails easily. However, its use is not supported for ASP.NET for a number of good reasons.
However however, if you took Erik Philips' suggestion and pre-generated all the thumbnails and stored them in the database alongside the originals, you would conceivably have a process of some sort (like a Windows service) that would periodically generate thumbs for rows that needed them. Because this process would generate the thumbs serially, you would not have the concerns about using System.Drawing as you would in an ASP.NET application (where you could easily have multiple threads gobbling up the relatively scarce system resources that System.Drawing wraps).
Edit: I just noticed the MVC tags. I don't know if System.Drawing is usable with MVC, or whether it's been superseded by something else. Generally, .NET has always had built-in useful graphics libraries that can do most simple things easily (I won't say it does simple things simply, as evidenced by the 30 overloads of the Graphics.DrawImage(...) method), so I expect you can still do this in MVC.
Don't reinvent a wheel ! There is a very nice, free (open-source in fact), pure .NET library, usable with API or handler :
http://imageresizing.net/
It supports very high quality resizing, converting to bunch of formats, auto-cropping, rotating, watermarking...
And if you think "nah, i can do it myself!", here is 20 reasons why you shouldnt :
http://nathanaeljones.com/163/20-image-resizing-pitfalls/
Here is routine that I use for making thumbnails :
public void MakeThumbnail(string imagePath)
{
// Image exists?
if (string.IsNullOrEmpty(imagePath)) throw new FileNotFoundException("Image does not exist at " + imagePath);
// Default values
string Filename = imagePath.ToLower().Replace(".jpg", "_thumb.jpg");
int Width = 100; // 180;
int Height = 75; // 135;
bool lSaved = false;
// Load image
Bitmap bitmap = new Bitmap(imagePath);
// If image is smaller than just save
try
{
if (bitmap.Width <= Width && bitmap.Height <= Height)
{
bitmap.Save(Filename, ImageFormat.Jpeg);
lSaved = true;
}
}
catch (Exception e)
{
throw new Exception(e.Message);
}
finally
{
bitmap.Dispose();
}
if (!lSaved)
{
Bitmap FinalBitmap = null;
// Making Thumb
try
{
bitmap = new Bitmap(imagePath);
int BitmapNewWidth;
decimal Ratio;
int BitmapNewHeight;
// Change size of image
Ratio = (decimal)Width / Height;
BitmapNewWidth = Width;
BitmapNewHeight = Height;
// Image processing
FinalBitmap = new Bitmap(BitmapNewWidth, BitmapNewHeight);
Graphics graphics = Graphics.FromImage(FinalBitmap);
graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphics.FillRectangle(Brushes.White, 0, 0, BitmapNewWidth, BitmapNewHeight);
graphics.DrawImage(bitmap, 0, 0, BitmapNewWidth, BitmapNewHeight);
// Save modified image
FinalBitmap.Save(Filename, ImageFormat.Jpeg);
}
catch (Exception e)
{
throw new Exception(e.Message);
}
finally
{
if (FinalBitmap != null) FinalBitmap.Dispose();
}
}
}

Categories

Resources