Save image file from qrCode or base64 in ASP.NET C# - c#

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());

Related

How to migrate using QRCoder; to using ZXing; in asp.net?

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);
}
}

How can I add an image in my database sqlite using dbContext WPF c#?

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();
}

Print usps Shipping Label

I already did a code for print label that is working fine on usps server . I just need to print pdf. How can I do this?
private void BindDetail()
{
//to test the upsp used below code
USPSManager m = new USPSManager("USERID", false);
Package p = new Package();
p.FromAddress.Contact = "John Smith";
p.FromAddress.Address2 = "475 L'Enfant Plaza, SW";
p.FromAddress.City = "Washington";
p.FromAddress.State = "DC";
p.FromAddress.Zip = "20260";
p.FromAddress.ZipPlus4 = "2060";
p.ToAddress.Contact = "Tom Customer";
p.ToAddress.Address1 = "STE 201";
p.ToAddress.Address2 = "6060 PRIMACY PKWY";
p.ToAddress.City = "Memphis";
p.ToAddress.State = "TN";
p.ToAddress.Zip = "20219";
p.ToAddress.ZipPlus4 = "2022";
p.WeightInOunces = 2;
p.ServiceType = ServiceType.Priority;
p.SeparateReceiptPage = false;
p.LabelImageType = LabelImageType.PDF;
p.PackageSize = PackageSize.Regular;
p.PackageType = PackageType.Flat_Rate_Box;
// p.ShippingLabel=
p = m.GetDeliveryConfirmationLabel(p);
}
As you mentioned that you already did the code and you are getting the response form server ; then in Order to print the label you just need to convert GetDeliveryConfirmationLabel to an image, you'll have a file called delivery_confirm.tif you can print that into an image. You can use the following from base64String to image
public Image Base64ToImage(string base64String)
{
// Convert Base64 String to byte[]
byte[] imageBytes = Convert.FromBase64String(base64String);
MemoryStream ms = new MemoryStream(imageBytes, 0,imageBytes.Length);
// Convert byte[] to Image
ms.Write(imageBytes, 0, imageBytes.Length);
Image image = Image.FromStream(ms, true);
return image;
}

Images are getting blur after retrieve from database

Following is the code to retrieve image from database and then saving it to a folder.
public string BinarytoNewsImage(int ID)
{
byte[] btimage = null;
string image = "";
string filename = null;
int mediaid;
DataSet dsNews = new DataSet();
adp = new SqlDataAdapter("Select Top 1 * from tblNew Where intNewId=" + ID, offcon);
adp.Fill(dsNews, "tblNews1");
if (dsNews.Tables["tblNews1"].Rows.Count > 0)
{
if (dsNews.Tables["tblNews1"].Rows[0]["strImage"] != DBNull.Value)
{
btimage = (byte[])dsNews.Tables["tblNews1"].Rows[0]["strImage"];
mediaid = Convert.ToInt32(dsNews.Tables["tblNews1"].Rows[0]["intMediaId"].ToString());
filename = dsNews.Tables["tblNews1"].Rows[0]["strfilename"].ToString();
image = BinarytoImage(btimage, mediaid);
}
else
{
filename = dsNews.Tables["tblNews1"].Rows[0]["strfilename"].ToString();
image = "http://www.patrika.com/media/" + filename;
}
}
return image;
}
public string BinarytoImage(byte[] stream, int ID)
{
string ImagePath = "";
string Image = ID + ".jpg";
var URL = System.Configuration.ConfigurationManager.AppSettings["ImagePath"].ToString();
string FolderName = new Uri(URL).LocalPath;
var help = HttpContext.Current.Server.MapPath(FolderName);
if (Directory.Exists(HttpContext.Current.Server.MapPath(FolderName)))
{
string[] files = Directory.GetFiles(HttpContext.Current.Server.MapPath(FolderName), ID + ".jpg");
if (files.Length > 0)
{
ImagePath = URL + ID + ".jpg";
}
else
{
using (MemoryStream MS = new MemoryStream(stream, 0, stream.Length))
{
MS.Write(stream, 0, stream.Length);
System.Drawing.Image img = System.Drawing.Image.FromStream(MS);
img.Save(help + ID + ".jpg", System.Drawing.Imaging.ImageFormat.Gif);
img.Dispose();
img = null;
ImagePath = URL + ID + ".jpg";
}
}
}
return ImagePath;
}
Everything is working fine the images are saving to a folder but my problem is images are getting blur after retrieval.
I just don't know the reason as when I am using another code for retrieval than images are coming fine but are not saved to folder:
DataSet dsNews = new DataSet();
adp = new SqlDataAdapter("Select Top 1 * from tblNew Where intNewId=901371", con);
adp.Fill(dsNews, "tblNews1");
if (dsNews.Tables["tblNews1"].Rows[0]["strImage"] != DBNull.Value)
{
byte[] btimage = (byte[])dsNews.Tables["tblNews1"].Rows[0]["strImage"];
Response.ContentType = "image/jpeg";
Response.BinaryWrite(btimage);
}
I need those images to be saved to folder so that I don't have to call database after once image comes.
Wouldn't it help to change this line
img.Save(help + ID + ".jpg", System.Drawing.Imaging.ImageFormat.Gif);
to store it as JPEG rather? as that's the source format
EDIT:
Your are not moving the stream pointer back to the start.
Try change these lines:
using (MemoryStream MS = new MemoryStream(stream, 0, stream.Length))
{
MS.Write(stream, 0, stream.Length);
System.Drawing.Image img = System.Drawing.Image.FromStream(MS);
...
To
using (MemoryStream MS = new MemoryStream(stream, 0, stream.Length))
{
MS.Write(stream, 0, stream.Length);
MS.Seek(0, SeekOrigin.Begin);
System.Drawing.Image img = System.Drawing.Image.FromStream(MS);
...
I write the common method, all is ok.
Maybe your byte[]stream is not right,pls check.
byte[] stream = File.ReadAllBytes(#"D:\YWG\123.jpg");
using (MemoryStream MS = new MemoryStream(stream, 0, stream.Length))
{
MS.Write(stream, 0, stream.Length);
using (Image img = Image.FromStream(MS))
{
img.Save(#"D:\dd.jpg", System.Drawing.Imaging.ImageFormat.Gif);
}
}
I see the dest file "dd.jpg" is ok.

NEED HELP.crop image while streaming it from IP cam

I have a monitoring system and I want to save a snapshot from a camera when alarm trigger. I have tried many methods to do that…and it’s all working fine.
string ImageName = #"E:\snapshot\pic" + imageid + ".jpg";
WebClient webclient = new WebClient();
webclient.Credentials = new NetworkCredential("admin", "pass");
Uri url = new Uri("http://" + ip + "/cgi-bin/cmd/encoder?SNAPSHOT");
webclient.DownloadFileAsync(url, ImageName);
webclient.Dispose();
the image coming from the cam is(1280*1024). i want to crop the image to get (500*500) Pixel
private void button2_Click(object sender, EventArgs e)
{
string ImageFrom = #"c:\3.jpg";
byte[] imageData = ReadFile(ImageFrom);
byte[] data = CropPicture(imageData, 500, 500);
SqlConnection cn = new SqlConnection("Data Source=.;Initial Catalog=test;Integrated Security=True");
string qry = "insert into val (id,img) values (#OriginalPath, #ImageData)";
SqlCommand SqlCom = new SqlCommand(qry, cn);
SqlCom.Parameters.Add(new SqlParameter("#OriginalPath",(object)"123"));
SqlCom.Parameters.Add(new SqlParameter("#ImageData", (object)data));
cn.Open();
SqlCom.ExecuteNonQuery();
}
byte[] ReadFile(string sPath)
{
byte[] data = null;
FileInfo fInfo = new FileInfo(sPath);
long numBytes = fInfo.Length;
FileStream fStream = new FileStream(sPath, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fStream);
data = br.ReadBytes((int)numBytes);
return data;
}
public static byte[] CropPicture(byte[] imgFile, int targetW, int targetH)
{
Image imgPhoto = Image.FromStream(new MemoryStream(imgFile));
int targetX = (imgPhoto.Width - targetW) / 2;
int targetY = (imgPhoto.Height - targetH) / 2;
Bitmap bmpPhoto = new Bitmap(targetW, targetH, PixelFormat.Format24bppRgb);
bmpPhoto.SetResolution(80, 60);
Graphics gfxPhoto = Graphics.FromImage(bmpPhoto);
gfxPhoto.SmoothingMode = SmoothingMode.AntiAlias;
gfxPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;
gfxPhoto.PixelOffsetMode = PixelOffsetMode.HighQuality;
gfxPhoto.DrawImage(imgPhoto, new Rectangle(0, 0, targetW, targetH), targetX, targetY, targetW, targetH, GraphicsUnit.Pixel);
MemoryStream mm = new MemoryStream();
bmpPhoto.Save(mm, System.Drawing.Imaging.ImageFormat.Jpeg);
// Dispose of all the objects to prevent memory leaks
imgPhoto.Dispose();
bmpPhoto.Dispose();
gfxPhoto.Dispose();
return mm.GetBuffer();
}
then insert it in the sql database
i got a code to crop the image.and i know how to insert image into sql database
but it all need to read the image as a file in the pc.
i stream the image then save it
then get it and crop it and insert it into db
PLEASE can any one tell me how to get the stream without the need to save it
You should be able to use something like this... (not tested)
Image img = Image.FromStream((new WebClient()).OpenRead("a"));

Categories

Resources