Implement Barcode in MVC - c#

I want to Implement Barcode in MVC web App hosted on IIS, for Super Store. After 3 day research i found an example on google but that was not in MVC. Please tell me how can i Implement this code in MVC, so when i pass a string barcode image display in my view
public void CreateBarcode(string code)
{
var myBitmap = new Bitmap(500, 50);
var g = Graphics.FromImage(myBitmap);
var jgpEncoder = GetEncoder(ImageFormat.Jpeg);
g.Clear(Color.White);
var strFormat = new StringFormat { Alignment = StringAlignment.Center };
g.DrawString(code, new Font("Free 3 of 9", 50), Brushes.Black, new RectangleF(0, 0, 500, 50), strFormat);
var myEncoder = System.Drawing.Imaging.Encoder.Quality;
var myEncoderParameters = new EncoderParameters(1);
var myEncoderParameter = new EncoderParameter(myEncoder, 100L);
myEncoderParameters.Param[0] = myEncoderParameter;
myBitmap.Save(#"E:\Barcode.jpg", jgpEncoder, myEncoderParameters);
}
public ImageCodecInfo GetEncoder(ImageFormat format)
{
var codecs = ImageCodecInfo.GetImageDecoders();
foreach (var codec in codecs)
{
if (codec.FormatID == format.Guid)
{
return codec;
}
}
return null;
}

It looks like you know how to make a barcode and need to know how to get it from a controller to your page. Here is a little code that may help you put it all together.
in your page
<img src="#Url.Action("Barcode", new { code = "*ABC123*" })" alt="" />
in your controller
public ActionResult Barcode(string code)
{
var myBitmap = new Bitmap(500, 50);
var g = Graphics.FromImage(myBitmap);
// the code that makes the barcode
// the code that makes the barcode
// the code that makes the barcode
// Put the image into a stream to return
MemoryStream ms = new MemoryStream();
myBitmap.Save(ms, ImageFormat.Png);
// Reset the stream position before returning it
ms.Position = 0;
return new FileStreamResult(ms, "image/png");
}

Related

Resize an image after upload and before saving it into the db

I have a simple web application (ASP.NET MVC 5 C#) which allows users to upload several files (images actually).
Currently it works well, the images are stored into the data base and I can read them later.
But I want to resize the images before saving them into the db, since the user can upload extremely big images.
Here is my controller:
public ActionResult Create(Annonce annonce, IEnumerable<HttpPostedFileBase> photos)
{
if (ModelState.IsValid)
{
// Read each uploaded files and add if into the collection
foreach (HttpPostedFileBase fichier in photos)
{
if (fichier != null && fichier.ContentLength > 0)
{
// Making a new object
var photo = new Photo
{
FileName = System.IO.Path.GetFileName(fichier.FileName),
ContentType = fichier.ContentType
};
using (var reader = new System.IO.BinaryReader(fichier.InputStream))
{
photo.Content = reader.ReadBytes(fichier.ContentLength);
}
// Add the current image to the collection
annonce.Photos.Add(photo);
}
}
db.Annonces.Add(annonce);
db.SaveChanges();
return RedirectToAction("Details", new { id = annonce.ID });
}
return View(annonce);
}
How can I resize my images and still be able to save them into the db?
Is-it even possible?
Thanks!
This code will perform a high quality resizing.(means you wont lose very much)
public static Bitmap ResizeImage(Image image, int width, int height)
{
var destRect = new Rectangle(0, 0, width, height);
var destImage = new Bitmap(width, height);
destImage.SetResolution(image.HorizontalResolution, image.VerticalResolution);
using (var graphics = Graphics.FromImage(destImage))
{
graphics.CompositingMode = CompositingMode.SourceCopy;
graphics.CompositingQuality = CompositingQuality.HighQuality;
graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphics.SmoothingMode = SmoothingMode.HighQuality;
graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
using (var wrapMode = new ImageAttributes())
{
wrapMode.SetWrapMode(WrapMode.TileFlipXY);
graphics.DrawImage(image, destRect, 0, 0, image.Width,image.Height, GraphicsUnit.Pixel, wrapMode);
}
}
return destImage;
}
Call ResizeImage() and assign it to a bitmap which you'll insert into your database.goodluck
you can convert it to byte array and than store it in your db as byte type
public byte[] imageToByteArray(System.Drawing.Image imageIn)
{
MemoryStream ms = new MemoryStream();
imageIn.Save(ms,System.Drawing.Imaging.ImageFormat.Gif);
return ms.ToArray();
}
you can do the same but inverted to get it out and display it as image from the DB:
public Image byteArrayToImage(byte[] byteArrayIn)
{
MemoryStream ms = new MemoryStream(byteArrayIn);
Image returnImage = Image.FromStream(ms);
return returnImage;
}
You also approach to ImageResizer as link below:
http://www.c-sharpcorner.com/article/image-resize-in-asp-net-mvc-using-image-resizer/

Why cant I use Gma.QrCodeNet.Encoding.Windows.Render?

I'm using QrCode.Net library version 0.3 and I need to use Gma.QrCodeNet.Encoding.Windows.Render in order to create images with qrcode ISizeCalculation but I'm missing somethig or there's another version outhere. What can be the problem?
Anyway I found a solution for people with the same problem and they wanna create images with the same fixed size. Here is the code:
private void gen_qr_file(string file_name, string content, int image_size)
{
string new_file_name = file_name;
QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.H);
QrCode qrCode = new QrCode();
qrEncoder.TryEncode(content, out qrCode);
Renderer renderer = new Renderer(image_size, Brushes.Black, Brushes.White);
MemoryStream ms = new MemoryStream();
renderer.WriteToStream(qrCode.Matrix, ms, ImageFormat.Png);
var image = new Bitmap(Image.FromStream(ms), new Size(new Point(200, 200)));
image.Save(new_file_name + ".png", ImageFormat.Png);
}
This generate a png image of 200x200 pixels with the qrcode.
The library itself has a method to do this, but I need to include the RENDER thing and I can't. Someone knows what's the problem?
private void gen_qr_file(string file_name, string content, int image_size) {
string new_file_name = file_name;
QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.H);
QrCode qrCode = new QrCode();
qrEncoder.TryEncode(content, out qrCode);
Renderer renderer = new Renderer(image_size, Brushes.Black, Brushes.White);
MemoryStream ms = new MemoryStream();
renderer.WriteToStream(qrCode.Matrix, ms, ImageFormat.Png);
var imageTemp = new Bitmap(ms);
var image = new Bitmap(imageTemp, new Size(new Point(image_size, image_size)));
image.Save(new_file_name + ".png", ImageFormat.Png);
}
Note: Only 2 lines are modified. I hope it helps somebody.
Use FixedCodeSize. See example below which will produce a 400x400px image, with each 'module' (block) getting smaller the more data is added.
var qrEncoder = new QrEncoder(ErrorCorrectionLevel.M);
var qrCode = qrEncoder.Encode("my value");
var renderer = new GraphicsRenderer(new FixedCodeSize(400, QuietZoneModules.Zero), Brushes.Black, Brushes.White);
renderer.WriteToStream(qrCode.Matrix, ImageFormat.Png, /* OUTPUT STREAM */);
I had to include both of the following statements:
using Gma.QrCodeNet.Encoding;
using Gma.QrCodeNet.Encoding.Windows.Controls;
Also, how big is Gma.QrCodeNet.Encoding.dll ?
It should be over 80K or you have the wrong one.
I had the same issue.
This is my implementation Only change GraphicsRenderer
private string gen_qr_file(string file_name, string content, int image_size)
{
string new_file_name = file_name;
QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.H);
QrCode qrCode = new QrCode();
qrEncoder.TryEncode(content, out qrCode);
GraphicsRenderer renderer = new GraphicsRenderer(
new FixedCodeSize(400, QuietZoneModules.Zero),
Brushes.Black,
Brushes.White);
MemoryStream ms = new MemoryStream();
renderer.WriteToStream(qrCode.Matrix, ImageFormat.Png, ms);
var imageTemp = new Bitmap(ms);
var image = new Bitmap(imageTemp, new Size(new Point(200, 200)));
image.Save(new_file_name, ImageFormat.Png);
return new_file_name;
}

Image Resizing from SQL Database on the fly with MVC2

I have a simple MVC2 app that uploads a file from the browser to an MS SQL database as an Image blob.
Then I can return the results with something like:
public FileContentResult ShowPhoto(int id)
{
TemporaryImageUpload tempImageUpload = new TemporaryImageUpload();
tempImageUpload = _service.GetImageData(id) ?? null;
if (tempImageUpload != null)
{
byte[] byteArray = tempImageUpload.TempImageData;
return new FileContentResult (temp, "image/jpeg");
}
return null;
}
But I want to return these images resized as both thumbnails and as a gallery-sized view. Is this possible to do within this Result? I've been playing around with the great imageresizer.net but it seems to want to store the images on my server which I want to avoid. Is it possible to do this on the fly..?
I need to keep the original file and don't, if possible, want to store the images as files on the server.
Thanks for any pointers!
ImageResizer.NET allows you to pass a stream to it for resizing, see Managed API usage
The method you'd use is:
ImageResizer.ImageBuilder.Current.Build(object source, object dest, ResizeSettings settings)
I modified your method to go about it this way, but it is untested. Hope it helps.
public FileContentResult ShowPhoto(int id)
{
TemporaryImageUpload tempImageUpload = new TemporaryImageUpload();
tempImageUpload = _service.GetImageData(id) ?? null;
if (tempImageUpload != null)
{
byte[] byteArray = tempImageUpload.TempImageData;
using(var outStream = new MemoryStream()){
using(var inStream = new MemoryStream(byteArray)){
var settings = new ResizeSettings("maxwidth=200&maxheight=200");
ImageResizer.ImageBuilder.Current.Build(inStream, outStream, settings);
var outBytes = outStream.ToArray();
return new FileContentResult (outBytes, "image/jpeg");
}
}
}
return null;
}
There was a recent Hanselminutes podcast on Image Resizing with Nathanael Jones discussing some of the pitfalls of image resizing.
Even if you do not have 30 odd minutes to listen to the full podcast, the show notes point to some interesting resizing pitfalls, as well as an image resizing library also written by Nathanael Jones.
You could resize the image on the fly:
public void ResizeImage(Stream input, Stream output, int newWidth, int maxHeight)
{
using (var srcImage = Image.FromStream(input))
{
int newHeight = srcImage.Height * newWidth / srcImage.Width;
if (newHeight > maxHeight)
{
newWidth = srcImage.Width * maxHeight / srcImage.Height;
newHeight = maxHeight;
}
using (var newImage = new Bitmap(newWidth, newHeight))
using (var gr = Graphics.FromImage(newImage))
{
gr.SmoothingMode = SmoothingMode.AntiAlias;
gr.InterpolationMode = InterpolationMode.HighQualityBicubic;
gr.PixelOffsetMode = PixelOffsetMode.HighQuality;
gr.DrawImage(srcImage, new Rectangle(0, 0, newWidth, newHeight));
newImage.Save(output, ImageFormat.Jpeg);
}
}
}
and then you could have 2 controller actions (one that displays the full image size and one that displays a thumbnail):
public ActionResult Thumbnail(int id)
{
var tempImageUpload = new TemporaryImageUpload();
tempImageUpload = _service.GetImageData(id) ?? null;
if (tempImageUpload == null)
{
return HttpNotFound();
}
using (var input = new MemoryStream(tempImageUpload.TempImageData))
using (var output = new MemoryStream())
{
ResizeImage(input, output, 640, 1000);
return File(output.ToArray(), "image/jpeg");
}
}

Code freezes my application

This code extremly freezes the WPF application.
Is there ANY chance to fix it?
var getScreenshot = Task.Factory.StartNew(() =>
{
Dispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle, new ThreadStart(() => {
#region Main
try
{
Graphics gfx;
Bitmap bmp = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
gfx = Graphics.FromImage(bmp);
WindowInteropHelper windowInteropHelper = new WindowInteropHelper(this);
Screen screen = Screen.FromHandle(windowInteropHelper.Handle);
gfx.CopyFromScreen(screen.Bounds.X, screen.Bounds.Y, 0, 0, screen.Bounds.Size, CopyPixelOperation.SourceCopy);
MemoryStream ms = new MemoryStream();
byte[] bitmapData = null;
using (bmp)
{
bmp.SetResolution(72, 72);
ImageCodecInfo myImageCodecInfo;
myImageCodecInfo = GetEncoderInfo("image/jpeg");
System.Drawing.Imaging.Encoder myEncoder;
myEncoder = System.Drawing.Imaging.Encoder.Quality;
EncoderParameters encoderParameters = new EncoderParameters();
EncoderParameter encoderParameter = new EncoderParameter(myEncoder, 25L);
encoderParameters.Param[0] = encoderParameter;
bmp.Save(ms, myImageCodecInfo, encoderParameters);
bitmapData = ms.ToArray();
}
if (bitmapData != null)
DataProvider.UpdateScreen(((PlayerConfiguration)App.Current.Properties["PlayerConfig"]).InstallationKey, bitmapData);
}
catch (Exception ex)
{
#region Error
LogEntry l = new LogEntry();
l.Message = string.Format("{0}", ex.Message);
l.Title = "GetScreen() Error";
l.Categories.Add(Category.General);
l.Priority = Priority.Highest;
CustomLogger.WriteErrorLog(l, "GetScreen");
#endregion
}
#endregion
}));
}, TaskCreationOptions.LongRunning)
.ContinueWith(x => x.Dispose());
Yes, just don't dispatch to the UI thread for the whole thing. Only put the smallest amount of code into the Invoke call that you can get away with. It should be when you're actually updating the UI. Since the whole thing is in the invoke call in your code, the UI is blocked until the whole thing finishes.

How to preserve png transparency?

I created a function to allow uploaded transparent .png files to be inserted into a SQL Server database and the displayed on a web page via an HttpHandler.
While this all works, the png transparency changes to black when it's viewed on the web page. Is there a way of preserving the transparency?
Here's my image service which inserts into the database from the MVC controller:
public void AddImage(int productId, string caption, byte[] bytesOriginal)
{
string jpgpattern = ".jpg|.JPG";
string pngpattern = ".png|.PNG";
string pattern = jpgpattern;
ImageFormat imgFormat = ImageFormat.Jpeg;
if (caption.ToLower().EndsWith(".png"))
{
imgFormat = ImageFormat.Png;
pattern = pngpattern;
}
ProductImage productImage = new ProductImage();
productImage.ProductId = productId;
productImage.BytesOriginal = bytesOriginal;
productImage.BytesFull = Helpers.ResizeImageFile(bytesOriginal, 600, imgFormat);
productImage.BytesPoster = Helpers.ResizeImageFile(bytesOriginal, 198, imgFormat);
productImage.BytesThumb = Helpers.ResizeImageFile(bytesOriginal, 100, imgFormat);
productImage.Caption = Common.RegexReplace(caption, pattern, "");
productImageDao.Insert(productImage);
}
And here's the "ResizeImageFile" helper function:
public static byte[] ResizeImageFile(byte[] imageFile, int targetSize, ImageFormat imageFormat)
{
using (System.Drawing.Image oldImage = System.Drawing.Image.FromStream(new MemoryStream(imageFile)))
{
Size newSize = CalculateDimensions(oldImage.Size, targetSize);
using (Bitmap newImage = new Bitmap(newSize.Width, newSize.Height, PixelFormat.Format24bppRgb))
{
using (Graphics canvas = Graphics.FromImage(newImage))
{
canvas.SmoothingMode = SmoothingMode.AntiAlias;
canvas.InterpolationMode = InterpolationMode.HighQualityBicubic;
canvas.PixelOffsetMode = PixelOffsetMode.HighQuality;
canvas.DrawImage(oldImage, new Rectangle(new Point(0, 0), newSize));
MemoryStream m = new MemoryStream();
newImage.Save(m, imageFormat);
return m.GetBuffer();
}
}
}
}
What do I need to do to preserve the png transparency? Please show examples. I'm seriously not an expert with image manipulation.
Thanks.
Maybe try changing pixel format form PixelFormat.Format24bppRgb to PixelFormat.Format32bppRgb. You need the extra 8 bits to hold the alpha channel.
Using PixelFormat.Format32bppRgb didn't work for me. What worked however is using oldImage.PixelFormat when drawing the new image. So the corresponding line of code becomes:
using (Bitmap newImage = new Bitmap(newSize.Width, newSize.Height, oldImage.PixelFormat))

Categories