How to migrate using QRCoder; to using ZXing; in asp.net , Because I learn How to Generate QR Code Using ASP.NET with
https://www.c-sharpcorner.com/blogs/how-to-generate-qr-code-using-asp-net
website but code in website use QRCoder library not support UTF-8 encoding , I have migrate QRCoder library code at line 16 - line 31 to ZXing library with
https://github.com/ritesh9835/QrCode
https://github.com/ritesh9835/QrCode/blob/master/QRcodeDemo/QRcodeDemo/Controllers/HomeController.cs
website instead QRCoder library code at line 16 - line 31 (Sample library code QRCoder and Zxing at the bottom).
QRCoder Library code.
using QRCoder;
using System;
using System.Drawing;
using System.IO;
namespace QRCode_Demo
{
public partial class QRCode : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnGenerate_Click(object sender, EventArgs e)
{
string code = txtQRCode.Text;
QRCodeGenerator qrGenerator = new QRCodeGenerator();
QRCodeGenerator.QRCode qrCode = qrGenerator.CreateQrCode(code, QRCodeGenerator.ECCLevel.Q);
System.Web.UI.WebControls.Image imgBarCode = new System.Web.UI.WebControls.Image();
imgBarCode.Height = 150;
imgBarCode.Width = 150;
using (Bitmap bitMap = qrCode.GetGraphic(20))
{
using (MemoryStream ms = new MemoryStream())
{
bitMap.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
byte[] byteImage = ms.ToArray();
imgBarCode.ImageUrl = "data:image/png;base64," + Convert.ToBase64String(byteImage);
}
PlaceHolder1.Controls.Add(imgBarCode);
}
}
}
}
Zxing Library code to instead QRCoder library code at line 16 - line 31.
private string GenerateQRCode(string qrcodeText)
{
string folderPath = "~/Images/";
string imagePath = "~/Images/QrCode.jpg";
// create new Directory if not exist
if (!Directory.Exists(Server.MapPath(folderPath)))
{
Directory.CreateDirectory(Server.MapPath(folderPath));
}
var barcodeWriter = new BarcodeWriter();
barcodeWriter.Format = BarcodeFormat.QR_CODE;
var result = barcodeWriter.Write(qrcodeText);
string barcodePath = Server.MapPath(imagePath);
var barcodeBitmap = new Bitmap(result);
using (MemoryStream memory = new MemoryStream())
{
using (FileStream fs = new FileStream(barcodePath, FileMode.Create, FileAccess.ReadWrite))
{
barcodeBitmap.Save(memory, ImageFormat.Jpeg);
byte[] bytes = memory.ToArray();
fs.Write(bytes, 0, bytes.Length);
}
}
return imagePath;
}
You mean like this ?
protected void btnGenerate_Click(object sender, EventArgs e)
{
string code = txtQRCode.Text;
var barcodeWriter = new BarcodeWriter();
barcodeWriter.Format = BarcodeFormat.QR_CODE;
barcodeWriter.Options.Margin = 0;
barcodeWriter.Options.Width = 150;
barcodeWriter.Options.Height = 150;
System.Web.UI.WebControls.Image imgBarCode = new System.Web.UI.WebControls.Image();
imgBarCode.Height = 150;
imgBarCode.Width = 150;
using (Bitmap bitMap = barcodeWriter.Write(code))
{
using (MemoryStream ms = new MemoryStream())
{
bitMap.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
byte[] byteImage = ms.ToArray();
imgBarCode.ImageUrl = "data:image/png;base64," + Convert.ToBase64String(byteImage);
}
PlaceHolder1.Controls.Add(imgBarCode);
}
}
Related
I want to save qrCode as image file in application path so that I can call it on report which is created in Crystal Report.
How to save qrCode as image file or convert base64 to an image and save on physical location?
This is my code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
TextBox6.Text = GenerateAndGetString();
QRCodeGenerator qrGenerator = new QRCodeGenerator();
QRCodeData qrCodeData = qrGenerator.CreateQrCode(TextBox6.Text, QRCodeGenerator.ECCLevel.Q);
QRCode qrCode = new QRCode(qrCodeData);
Bitmap qrCodeImage = qrCode.GetGraphic(20);
using (Bitmap bitMap = qrCode.GetGraphic(20))
{
using (MemoryStream ms = new MemoryStream())
{
bitMap.Save(ms, ImageFormat.Png);
byte[] byteImage = ms.ToArray();
img.Src = "data:image/png;base64," + Convert.ToBase64String(byteImage);
}
}
}
}
public String GenerateAndGetString()
{
var sellername = TextBox1.Text;
var vatregistration = TextBox2.Text;
var timestamp = TextBox3.Text;
var invoiceamount = TextBox4.Text;
var vatamoun = TextBox5.Text;
return ConvertBase64(sellername, vatregistration, timestamp, invoiceamount, vatamoun);
}
You already got the image as byte-array, so you could do something like this:
System.IO.File.WriteAllBytes(path, ms.ToArray());
I want to add an image to the database in an image column in byte form
I am using SQLite to save my database data and WPF Application using dbContext c# to write my code
can anyone help me please?
private void ChooseImageButtonClick(object sender, RoutedEventArgs e)
{
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
dlg.Filter = "Choose Image(*.JPG;*.PNG;*.GIF)|*.jpg;*.png;*.gif";
if (dlg.ShowDialog() == true)
{
string FileName = dlg.FileName.ToString();
BitmapImage bitmap = new BitmapImage();
bitmap.BeginInit();
bitmap.UriSource = new Uri(FileName);
bitmap.EndInit();
ImageBox.Source = bitmap;
}
}
private void savebtnClick(object sender, RoutedEventArgs e)
{
using (DatabaseContext dbContext = new DatabaseContext())
{
Person p = new Person
{
Id = int.Parse(Idtextbox.Text),
Name = Nametextbox.Text,
Image = image
};
dbContext.Person.Add(p);
dbContext.SaveChanges();
RefreshList();
}
}
Just convert BitmapImage to byte array first
byte[] image;
JpegBitmapEncoder encoder = new JpegBitmapEncoder();
encoder.QualityLevel = 100;
using (MemoryStream ms = new MemoryStream())
{
encoder.Frames.Add(BitmapFrame.Create((BitmapSource)ImageBox.Source));
encoder.Save(ms);
image = ms.ToArray();
}
encoder = null;
And in your database context - add
using (DatabaseContext dbContext = new DatabaseContext())
{
Part part = new Part();
part.Id = int.Parse(TextBoxID.Text);
part.Name = TextBoxName.Text;
part.Image = image;
dbContext.Part.Add(part);
dbContext.SaveChanges();
RefreshPartsList();
}}
To convert byte array back to BitmapImage :
byte[] imageData = part.Image; // that you get from db
if (imageData == null || imageData.Length == 0)
{
//Show error msg or return here;
return;
}
var image = new BitmapImage();
using (var ms = new System.IO.MemoryStream(imageData))
{
image.BeginInit();
image.CacheOption = BitmapCacheOption.OnLoad;
image.StreamSource = ms;
image.EndInit();
image.Freeze();
}
Add Property in 'Part' class
public byte[] ImageCol { get; set; }
Then from "OpenFileDialog" create Image from selected file. For Example
OpenFileDialog openFileDialog = new OpenFileDialog
{
Filter = "Image Files(*.BMP;*.JPG;*.JPEG;*.GIF;*.PNG)|*.BMP;*.JPG;*.JPEG;*.GIF;*.PNG",
InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
};
if (openFileDialog.ShowDialog()==DialogResult.OK)
{
var imageFromFile = System.Drawing.Image.FromFile(openFileDialog.FileName);
part.ImageCol = imageFromFile.ConvertBitmapImagetoBytes();
}
Convert BitMap to byte[]
public static byte[] ConvertBitmapImagetoBytes(this Image image)
{
MemoryStream ms = new MemoryStream();
image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
return ms.ToArray();
}
I'm trying to stamp a QRCode on PDF documents when a user uploads them to a document library and checks it in with metadata (A new field called "DocumentCode").
From what I know, I'll have to check it out, read the DocumentCode value from the document checked out, generate a QRCode using "QRCODER" from NuGet, use PDFStamper to stamp it on the first page using iTextSharp.
I'm giving up on trying to resolve it without asking for help, so I'm here to ask for help.
This is the code I wrote:
using Microsoft.SharePoint;
using System.IO;
using System.Drawing;
using iTextSharp.text.pdf;
using QRCoder;
namespace WFA.CodeTestReceiver
{
public class CodeTestReceiver : SPItemEventReceiver
{
public override void ItemUpdated(SPItemEventProperties properties)
{
using (SPWeb web = properties.OpenWeb())
{
SPFile UploadedFile = properties.ListItem.File;
byte[] FileContent = UploadedFile.OpenBinary();
QRCodeGenerator qrCodeGen = new QRCodeGenerator();
QRCodeData qrCodeData = qrCodeGen.CreateQrCode(properties.ListItem["DocumentCode"].ToString(), QRCodeGenerator.ECCLevel.Q, true, false);
BitmapByteQRCode qrBitmap = new BitmapByteQRCode(qrCodeData);
byte[] qrBytes = qrBitmap.GetGraphic(6);
byte[] NewFile;
MemoryStream MS = new MemoryStream(qrBytes);
using (Stream iPDF = new MemoryStream(FileContent))
using (Stream iIMG = new MemoryStream(qrBytes))
using (Stream oPDF = new MemoryStream())
{
var reader = new PdfReader(iPDF);
var stamper = new PdfStamper(reader, oPDF);
var PDC = stamper.GetOverContent(1);
var pSize = reader.GetPageSize(1);
iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(iIMG);
Point P = new Point(0, 0);
P.X = 50;
P.Y = 700;
int Y = (int)(pSize.Height - P.Y);
image.SetAbsolutePosition(100, 300);
PDC.AddImage(image);
oPDF.CopyTo(MS);
NewFile = MS.ToArray();
stamper.Close();
}
SPFile sFile = web.Folders["CodeTest"].Files.Add(properties.ListItem.File.Name, NewFile, true);
}
base.ItemUpdated(properties);
}
public override void ItemCheckedIn(SPItemEventProperties properties)
{
using (SPWeb web = properties.OpenWeb())
{
SPFile UploadedFile = properties.ListItem.File;
byte[] FileContent = UploadedFile.OpenBinary();
QRCodeGenerator qrCodeGen = new QRCodeGenerator();
QRCodeData qrCodeData = qrCodeGen.CreateQrCode(properties.ListItem["DocumentCode"].ToString(), QRCodeGenerator.ECCLevel.Q, true, false);
BitmapByteQRCode qrBitmap = new BitmapByteQRCode(qrCodeData);
byte[] qrBytes = qrBitmap.GetGraphic(6);
byte[] NewFile;
MemoryStream MS = new MemoryStream(qrBytes);
using (Stream iPDF = new MemoryStream(FileContent))
using (Stream iIMG = new MemoryStream(qrBytes))
using (Stream oPDF = new MemoryStream())
{
var reader = new PdfReader(iPDF);
var stamper = new PdfStamper(reader, oPDF);
var PDC = stamper.GetOverContent(1);
var pSize = reader.GetPageSize(1);
iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(iIMG);
Point P = new Point(0, 0);
P.X = 50;
P.Y = 700;
int Y = (int)(pSize.Height - P.Y);
image.SetAbsolutePosition(100, 300);
PDC.AddImage(image);
oPDF.CopyTo(MS);
NewFile = MS.ToArray();
stamper.Close();
}
SPFile sFile = web.Folders["CodeTest"].Files.Add(properties.ListItem.File.Name, NewFile, true);
}
base.ItemCheckedIn(properties);
}
}
}
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;
}
Whenever I retrieve an image using my Generic Handler, I retrieve either an empty image or a broken image.
Here is my code.
aspx File:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
//imports
using DHELTASSys.Modules;
using System.Data;
using DHELTASSys.AuditTrail;
namespace DHELTASSys
{
public partial class EvaluateOffense : System.Web.UI.Page
{
DisciplineModuleBL discipline = new DisciplineModuleBL();
DHELTASSysAuditTrail audit = new DHELTASSysAuditTrail();
protected void Page_Load(object sender, EventArgs e)
{
string position = Session["Position"].ToString();
if (Session["EmployeeID"] == null)
{
Response.Redirect("LogIn.aspx");
} else if(position != "HR Manager")
{
Response.Redirect("AccessDenied.aspx");
}
discipline.Offense_emp_id = int.Parse(Session["OffenseID"].ToString());
DataTable dt = discipline.GetProof();
if (dt.Rows == null)
{
Label9.Visible = false;
Image1.Visible = false;
}
}
protected void btnEvaluate_Click(object sender, EventArgs e)
{
discipline.Offense_emp_id = int.Parse(Session["OffenseID"].ToString());
discipline.Decision = drpDecision.Text;
discipline.AddOffenseDecision();
audit.Emp_id = int.Parse(Session["EmployeeID"].ToString());
audit.AddAuditTrail(drpDecision.Text + "ed Employee's offense.");
}
}
}
Here is the handler:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
//imports
using System.Data;
using DHELTASSys.Modules;
using DHELTASSys.DataAccess;
namespace DHELTASSys
{
public class ShowImage : IHttpHandler, System.Web.SessionState.IRequiresSessionState
{
DisciplineModuleBL discipline = new DisciplineModuleBL();
public void ProcessRequest(HttpContext context)
{
if (context.Session["OffenseID"].ToString() == null) return;
int offense_emp_id = int.Parse(context.Session["OffenseID"].ToString());
discipline.Offense_emp_id = offense_emp_id;
DataTable dt = discipline.GetProof();
if (dt.Rows == null) return;
int id = 1;
string image = dt.Rows[0][1].ToString() + id;
string FileName = dt.Rows[0][0].ToString();
string FileContentType = dt.Rows[0][2].ToString();
Byte[] bytes = (Byte[])dt.Rows[0][1];
string imageBase64 = Convert.ToBase64String(bytes);
context.Response.ContentType = "image/" + FileContentType;
if (context.Request.QueryString["id"] == "1")
{
MemoryStream ms = new MemoryStream();
ms.Write(bytes, 0, bytes.Length);
context.Response.Buffer = true;
System.Drawing.Image imagen = System.Drawing.Image.FromStream(ms);
context.Response.BinaryWrite(bytes);
ms.Dispose();
}
else
{
return;
}
}
public bool IsReusable
{
get
{
return true;
}
}
}
}
And adding to that, here is my image object.
<asp:Image ID="Image1" runat="server" ImageUrl="~/ShowImage.ashx" />
I already tweaked my code in so many ways.
The image file is stored in SQL Server using the data type "Image"
As you can see, I'm using the session to retrieve the specified image from the Database.
I have no problem in accessing the session whatsoever.
Thanks in advance.
Your code seems a bit more complicated than necessary; you can write the binary data to the outputstream without needing to load it into a memory stream, and you're doing nothing with your System.Drawing.Image object. Try this:
context.Response.OutputStream.Write(bytes, 0, bytes.Length);
First, I don't see anything wrong with the way you are writing the image to the response stream. There's a few useless lines of code but I understand that as you said, you were tweaking your code in desperation. Basically, this should be good enough...
Byte[] bytes = (Byte[])dt.Rows[0][1];
context.Response.ContentType = "image/" + FileContentType;
if (context.Request.QueryString["id"] == "1")
{
context.Response.BinaryWrite(bytes);
context.ApplicationInstance.CompleteRequest(); //just to make sure the ASP.NET pipeline completes the request
}
else
{
return;
}
Now, that "should" work given that bytes has been correctly casted to a byte array. Make sure to add some proper exception handling and logging because I'm a bit suspicious that the problem it's somewhere else. So, follow these steps:
Clean up your code for better clarity
Debug the app
Implement some exception handling
Implement some sort of error logging
You should be able to get to the bottom of this issue since there's nothing wrong in sending an array of bytes using the BinaryWrite method
This is real example that pickup from my project
into page.cs set image url dynamically:
// for diffrent url using guid in url
imgProfilePic.ImageUrl = "GenericHandler_ShowImage.ashx?Ref=" + Guid.NewGuid().ToString() + "&n=" + lngEmployeeID;
into handler, get image by table adapter
// in handler
public void ProcessRequest(HttpContext context)
{
long EmployeeID = -1;
if (context.Request.QueryString["n"] != null)
EmployeeID = long.Parse(context.Request.QueryString["n"].ToString());
//else
// throw new ArgumentException("No parameter specified");
if (context.Request.QueryString["actid"] == "2")
{
ShowThumbPic(context, EmployeeID);
return;
}
//else ...
}
private void ShowThumbPic(HttpContext context, long EmployeeID)
{
context.Response.ContentType = "image/jpeg";
Stream myStream = GetEmpImage(EmployeeID);
byte[] myImgByteArray;
using (BinaryReader br = new BinaryReader(myStream))
{
myImgByteArray = br.ReadBytes((int)myStream.Length);
}
MemoryStream ms = new MemoryStream(byteArrayIn);
System.Drawing.Image img = System.Drawing.Image.FromStream(ms);
if (img.Height > 50 || img.Width > 50)
{
System.Drawing.Size siz = GetScaledSize(img.Size, new System.Drawing.Size(50, 50));
img = (System.Drawing.Image)ResizeImage(img, siz);
}
MemoryStream ms = new MemoryStream();
img.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
byte[] myBuffer = ms.ToArray();
int byteSeq = myBuffer.Length; //myStream.Read(myBuffer, 0, 4096);
if (byteSeq > 0)
context.Response.OutputStream.Write(myBuffer, 0, byteSeq);
}
private System.Drawing.Image GetEmployeeImage(long EmployeeID)
{
System.Drawing.Image img = null;
try
{
using (DAL.dstEmployeeTableAdapters.tbl_Employee_InfoTableAdapter ta = new DAL.dstEmployeeTableAdapters.tbl_Employee_InfoTableAdapter())
{
object obj = ta.spr_Employee_Info_GetPicture(EmployeeID);
if (obj != null)
{
MemoryStream ms = new MemoryStream((byte[])obj);
img = System.Drawing.Image.FromStream(ms);
}
}
}
catch (Exception x)
{
throw new Exception(Msg.Error_InDownloadPicture + x.Message);
}
return img;
}
public static Size GetScaledSize(Size ImageSize, Size FrameSize)
{
int newWidth = ImageSize.Width;
int newHeight = ImageSize.Height;
double ratioX = (double)FrameSize.Width / ImageSize.Width;
double ratioY = (double)FrameSize.Height / ImageSize.Height;
double ratio = Math.Min(ratioX, ratioY);
if (ratio < 1.0f) // if Frame is greater than image, resize it.
{
newWidth = (int)(ImageSize.Width * ratio);
newHeight = (int)(ImageSize.Height * ratio);
}
return new Size(newWidth, newHeight);
}
public static System.Drawing.Bitmap ResizeImage(System.Drawing.Image image, Size siz)
{
//a holder for the result
Bitmap result = new Bitmap(siz.Width, siz.Height);
// set the resolutions the same to avoid cropping due to resolution differences
result.SetResolution(image.HorizontalResolution, image.VerticalResolution);
//use a graphics object to draw the resized image into the bitmap
using (Graphics graphics = Graphics.FromImage(result))
{
//set the resize quality modes to high quality
graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
//draw the image into the target bitmap
graphics.DrawImage(image, 0, 0, result.Width, result.Height);
}
//return the resulting bitmap
return result;
}