Technologies: Visual Studio 2010 and Crystal Reports, MVC3 Web Application, multi tier app.
My web app build one report to label print. The report works fine but not generates the bar code. When I view the report the barcode field is blank. I already installed the IDAutomationHC39M and works in winforms project.
The code that generates the report:
public void Barcode()
{
BarCode report = new BarCode();
Barcodes barcodeDetails = new Barcodes();
DataTable dataTable = barcodeDetails._Barcodes;
for (int i = 0; i < 80; i++)
{
DataRow row = dataTable.NewRow();
string nome = "nome" + i;
decimal preco = i;
string barcode = i + "ADF" + i;
row["nome"] = nome;
row["preco"] = preco;
row["barcode"] = barcode;
dataTable.Rows.Add(row);
}
report.Database.Tables["Barcodes"].SetDataSource((DataTable)dataTable);
report.ExportToHttpResponse(ExportFormatType.PortableDocFormat, System.Web.HttpContext.Current.Response, false, "crReport");
}
Is more easy transform the barcode in a jpeg? If yes, how can i make this in crystal reports?
EDI I: I try change the code for:
for (int i = 0; i < 80; i++)
{
DataRow row = dataTable.NewRow();
string nome = "nome" + i;
decimal preco = i;
string barcode = "*" + i + "ADF" + i + "*";
row["nome"] = nome;
row["preco"] = preco;
System.Web.UI.WebControls.Image imgBarCode = new System.Web.UI.WebControls.Image();
using (Bitmap bitMap = new Bitmap(barcode.Length * 40, 80))
{
using (Graphics graphics = Graphics.FromImage(bitMap))
{
Font oFont = new Font("IDAutomationHC39M", 10);
PointF point = new PointF(2f, 2f);
SolidBrush blackBrush = new SolidBrush(Color.Black);
SolidBrush whiteBrush = new SolidBrush(Color.White);
graphics.FillRectangle(whiteBrush, 0, 0, bitMap.Width, bitMap.Height);
graphics.DrawString("*" + barcode + "*", oFont, blackBrush, point);
}
using (MemoryStream ms = new MemoryStream())
{
bitMap.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
byte[] byteImage = ms.ToArray();
Convert.ToBase64String(byteImage);
imgBarCode.ImageUrl = "data:image/png;base64," + Convert.ToBase64String(byteImage);
row["barcode"] = imgBarCode.ImageUrl;
}
}
dataTable.Rows.Add(row);
}
But no effects.
The process to display barcodes in asp.net app (MVC in my case) is really transform the font in an jpeg.
Step 1: get the value for barcode and add "*" in start and end, then creates the Bitmap, Font and Graphics.
DataRow row = dataTable.NewRow();
string barcode = "*" + ID.ToString() + VALOR_VENDA.Value.ToString() + "*";
row["nome"] = NOME_PRODUTO;
row["preco"] = VALOR_VENDA.Value;
int w = barcode.Length * 40;
Bitmap oBitmap = new Bitmap(w, 100);
Graphics oGraphics = Graphics.FromImage(oBitmap);
Font oFont = new Font("IDAutomationHC39M", 18);
PointF oPoint = new PointF(2f, 2f);
SolidBrush oBrushWrite = new SolidBrush(Color.Black);
SolidBrush oBrush = new SolidBrush(Color.White);
oGraphics.FillRectangle(oBrush, 0, 0, w, 100);
oGraphics.DrawString(barcode, oFont, oBrushWrite, oPoint);
Next use an MemoryStream to add the bitmap. Make sure that your dataset field is the type Byte[]. With the memorystream add to dataset the value .ToArray();
using (MemoryStream ms = new MemoryStream())
{
oBitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] byteImage = ms.ToArray();
row["barcode"] = byteImage;
}
dataTable.Rows.Add(row);
Related
private void GetData()
{
con.Open();
Cmd = new SqlCommand("Select Image,Name,Price from Product" ,con);
dr = Cmd.ExecuteReader();
while(dr.Read())
{
long len = dr.GetBytes(0, 0, null, 0, 0);
byte[] array = new byte[Convert.ToInt32(len)+ 1];
dr.GetBytes(0, 0, array, 0, Convert.ToInt32(len));
pic = new PictureBox();
pic.Width = 100;
pic.Height = 100;
pic.BackgroundImageLayout = ImageLayout.Zoom;
price = new Label();
price.Text = dr["price"].ToString();
price.Dock = DockStyle.Bottom;
price.TextAlign = ContentAlignment.MiddleCenter;
Names = new Label();
Names.Text = dr["name"].ToString();
Names.TextAlign = ContentAlignment.MiddleCenter;
MemoryStream ms = new MemoryStream(array);
Bitmap bitmap = new Bitmap(ms); // <--------(Error comes here)
pic.BackgroundImage = bitmap;
pic.Controls.Add(price);
pic.Controls.Add(Names);
flowLayoutPanel2.Controls.Add(pic);
}
con.Close();
}
I'm trying to get an image from SQL Server but the bitmap objects shows invalid parameters. the byte[] array seems to be causing this problem. Any ideas on how to fix it?
I have the newest SQL Server version as well.
Depending in the datatype in SQL you can just use
byte[] image = dr[“image”]
i created two images 1st one is Barcode Image and 2nd is SkuImage after that I Merged It in 3rd image(final Image). after Successfully Merged
i want to delete Barcode Image and Sku image from Specific folder, but when i try to delete image file it Gives me a error i.e "The process cannot access the file \Path\ because it is being used by another process".
before deleting i disposed the image like this "SkuImage.Dispose()" but it doesnt delete. How do i delete this?
barcodeImage = b.Encode(BarcodeLib.TYPE.CODE128, "001234", Color.Black, Color.White, 113, 18);
Bitmap SkuImage = new Bitmap(113, 18, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
RectangleF rectf = new RectangleF(10, 5, 113, 18);
Graphics graphics = Graphics.FromImage(SkuImage);
// SkuImage.SetPixel(10,10,Color.Blue);
graphics.DrawString(StringToEncode, new Font("Arial", 4), Brushes.Black, rectf);
b.SaveImage(MemStream, savetype);
MemStream.Close();
barcodeImage.Dispose();
SkuImage.Save(imgSkupath);
SkuImage.Dispose();
g.Clear(Color.White); //here change BG color of Image
g.DrawImage(Image.FromFile("E:\\" + #"Pankaj/BarcodeDemo/BarcodeDemo/BarcodeImage/" + Filename), new Point(15, 15));
g.DrawImage(Image.FromFile("E:\\" + #"Pankaj/BarcodeDemo/BarcodeDemo/BarcodeImage/Sku.jpg"), new Point(25, 30));
img.Save("E:\\" + #"Pankaj/BarcodeDemo/BarcodeDemo/BarcodeImage/FinalImage.jpeg", ImageFormat.Jpeg);
File.Delete("E:\\" + #"Pankaj/BarcodeDemo/BarcodeDemo/BarcodeImage/Sku.jpg");
File.Delete("E:\\" + #"Pankaj/BarcodeDemo/BarcodeDemo/BarcodeImage/" + Filename);
You should dispose every class that implements IDisposable. Then you can delete the image file.
string Filename = "Barcodeimage" + i + ".jpeg";
string imgsavepath = "E:\\Pankaj\\BarcodeDemo\\BarcodeDemo\\BarcodeImage\\" + "BarcodeImg.jpeg";
string imgSkupath = "E:\\Pankaj\\BarcodeDemo\\BarcodeDemo\\BarcodeImage\\" + "Sku.jpeg";
BarcodeLib.SaveTypes savetype = BarcodeLib.SaveTypes.UNSPECIFIED;
savetype = BarcodeLib.SaveTypes.JPG;
System.IO.FileStream MemStream = new FileStream(imgsavepath, FileMode.Create, FileAccess.Write);
System.Drawing.Image barcodeImage = null;
//Bitmap FinalImage = null;
BarcodeLib.Barcode b = new BarcodeLib.Barcode();
//b.IncludeLabel = true;
b.LabelFont = new Font("Arial", 5);
string sku = "SKU:VXN4214IN";
string StringToEncode = "16280/" + i + ' ' + sku;
Image img = new Bitmap(130, 50); //final image
Graphics g = Graphics.FromImage(img);
barcodeImage = b.Encode(BarcodeLib.TYPE.CODE128, "001234", Color.Black, Color.White, 113, 18);
Bitmap SkuImage = new Bitmap(113, 18, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
RectangleF rectf = new RectangleF(10, 5, 113, 18);
Graphics graphics = Graphics.FromImage(SkuImage);
// SkuImage.SetPixel(10,10,Color.Blue);
graphics.DrawString(StringToEncode, new Font("Arial", 4), Brushes.Black, rectf);
b.SaveImage(MemStream, savetype);
MemStream.Close();
barcodeImage.Dispose();
SkuImage.Save(imgSkupath);
graphics.Dispose();
SkuImage.Dispose();
g.Clear(Color.White); //here change BG color of Image
System.IO.FileStream fileStream1 = new FileStream("E:\\" + #"Pankaj/BarcodeDemo/BarcodeDemo/BarcodeImage/BarcodeImg.jpeg", FileMode.Open, FileAccess.Read);
System.IO.FileStream fileStream2 = new FileStream("E:\\" + #"Pankaj/BarcodeDemo/BarcodeDemo/BarcodeImage/Sku.jpeg", FileMode.Open, FileAccess.Read);
g.DrawImage(Image.FromStream(fileStream1), new Point(15, 15));
g.DrawImage(Image.FromStream(fileStream2), new Point(25, 30));
// g.DrawImage(Image.FromFile("E:\\" + #"Pankaj/BarcodeDemo/BarcodeDemo/BarcodeImage/" + Filename), new Point(15, 15));
//g.DrawImage(Image.FromFile("E:\\" + #"Pankaj/BarcodeDemo/BarcodeDemo/BarcodeImage/Sku.jpg"), new Point(25, 30));
img.Save("E:\\" + #"Pankaj/BarcodeDemo/BarcodeDemo/BarcodeImage/"+Filename, ImageFormat.Jpeg);
fileStream1.Close();
fileStream2.Close();
g.Dispose();
File.Delete("E:\\" + #"Pankaj/BarcodeDemo/BarcodeDemo/BarcodeImage/Sku.jpeg");
File.Delete("E:\\" + #"Pankaj/BarcodeDemo/BarcodeDemo/BarcodeImage/BarcodeImg.jpeg");
Dim _strImagePath = ""
Dim _strImageName = "image.jpg"
'Get the path
_strImagePath = "YOUR_IMAGE_PATH"
'Delete the image physically
Dim strImageName As New FileInfo(_strImagePath & _strImageName)
If strImageName.Exists Then
strImageName.Delete()
End If
I can dynamically create a barcode using sample tutorials.
This block of code is in a loop and generates a number of images determined by user input. The image is in a place holder and is displayed on the same webpage.
I want the user to be able to have all the images on a separate page or file for them to print, but I'm not quite sure the best approach to do that. I tried placing it in a session, but I only get 1 image as opposed to the amount the user entered.
System.Web.UI.WebControls.Image imgBarCode = new System.Web.UI.WebControls.Image();
using (Bitmap bitMap = new Bitmap(barCode.Length * 27, 100))
{
using (Graphics graphics = Graphics.FromImage(bitMap))
{
Font oFont = new Font("IDAutomationHC39M", 16);
PointF point = new PointF(2f, .2f);
SolidBrush blackBrush = new SolidBrush(Color.Black);
SolidBrush whiteBrush = new SolidBrush(Color.White);
graphics.FillRectangle(whiteBrush, 0, 0, bitMap.Width, bitMap.Height);
graphics.DrawString("*" + barCode + "*", oFont, blackBrush, point);
}
using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
{
bitMap.Save(ms, ImageFormat.Png);
byte[] byteImage = ms.ToArray();
Convert.ToBase64String(byteImage);
imgBarCode.ImageUrl = "data:image/png;base64," + Convert.ToBase64String(byteImage);
}
plBarCode.Controls.Add(imgBarCode);
}
I have 2 Apps (server - client ) .
The server is modified version of TVsharp (Application that stream local analog tv signal using RTLSDR)
Each frame of the streamed video is a grayscale array of bytes .
I have modified it so it re sizes and sends each frame for a client over TCP socket
The client is supposed to receive the frames through the socket as Image objects and displays them in a picture box
Im getting invalid parameters error .
After i added a delay (Thread.Sleep()) it started to display one frame and then it gives invalid parameter exception (after the sleeping time)
This is the part of TVsharp that dose the sending :
Grayscale is an array that contains the brightness for each pixel
private string drive = "E:\\";
private string file = "0";
private string extension = ".bmp";
private string path2 = "E:\\test\\";
private string fullpath;
private int file_counter = 0;
Bitmap bitmap2 = new Bitmap(_pictureWidth, _pictureHeight);
var data2 = bitmap2.LockBits(new Rectangle(Point.Empty, bitmap2.Size),
ImageLockMode.WriteOnly,PixelFormat.Format24bppRgb);
Marshal.Copy(GrayScaleValues, 0, data2.Scan0, GrayScaleValues.Length);
bitmap2.UnlockBits(data2);
bitmap2.Save(fullpath, System.Drawing.Imaging.ImageFormat.Bmp);
string Npath = path2 + file + extension;
Image img = Image.FromFile(fullpath);
// Size size = new Size(982, 543);
// ResizeImage(img, size);
Rectangle cropRect = new Rectangle(80, 0, 240, 175);
Bitmap target = new Bitmap(cropRect.Width, cropRect.Height);
using (Graphics g = Graphics.FromImage(target))
{
g.DrawImage(img, new Rectangle(0, 0, target.Width, target.Height), cropRect, GraphicsUnit.Pixel);
}
//double scale = 203 / 96;
int width = (int)(target.Width);
int height = (int)(target.Height);
BinaryWriter brn = new BinaryWriter(s);
System.Drawing.Bitmap bmpScaled = new System.Drawing.Bitmap(target, width, height);
bmpScaled.Save(Npath);
byte[] imageArray = File.ReadAllBytes(Npath);
sw.WriteLine(imageArray.Length.ToString());
sw.Flush();
// Thread.Sleep(500);
brn.Write(imageArray);
//Thread.Sleep(500);
_detectLevel = Convert.ToInt32(_maxSignalLevel * _detectorLevelCoef);
_agcSignalLevel = agcMaxLevel;
}
This client the client segment that suppose to get the frames and display them
flag = true;
TcpClient client = new TcpClient(textBox1.Text, Convert.ToInt32(textBox2.Text));
Stream s = client.GetStream();
StreamReader sr = new StreamReader(s);
StreamWriter sw = new StreamWriter(s);
sw.Flush();
BinaryFormatter formatter = new BinaryFormatter();
string msg = sr.ReadLine();
MessageBox.Show("It's working !! the message is " + msg);
BinaryReader Brn = new BinaryReader(s);
Thread.Sleep(5000);
while (flag)
{
// Thread.Sleep(5000);
int size = Convert.ToInt32(sr.ReadLine());
label3.Text = "Size is " + size;
byte[] imagerray = Brn.ReadBytes(size);
MemoryStream ms = new MemoryStream(imagerray);
Thread.Sleep(10000);
Image image = Image.FromStream(ms);
ResizeImage(image, this.Size);
pictureBox1.Image = image;
Thread.Sleep(10);
}
}
I'm trying to convert an XPS with WPF.
The idea is that these images can be loaded with silverlight 4, for this I am using the following code:
// XPS Document
XpsDocument xpsDoc = new XpsDocument(xpsFileName, System.IO.FileAccess.Read);
FixedDocumentSequence docSeq = xpsDoc.GetFixedDocumentSequence();
// The number of pages
PageCount = docSeq.References[0].GetDocument(false).Pages.Count;
DocumentPage sizePage = docSeq.DocumentPaginator.GetPage(0);
PageHeight = sizePage.Size.Height;
PageWidth = sizePage.Size.Width;
// Scale dimensions from 96 dpi to 600 dpi.
double scale = 300/ 96;
// Convert a XPS page to a PNG file
for (int pageNum = 0; pageNum < PageCount; pageNum++)
{
DocumentPage docPage = docSeq.DocumentPaginator.GetPage(pageNum);
BitmapImage bitmap = new BitmapImage();
RenderTargetBitmap renderTarget =
new RenderTargetBitmap((int)(scale * (docPage.Size.Height + 1)),
(int)(scale * (docPage.Size.Height + 1)),
scale * 96,
scale * 96, PixelFormats.Pbgra32);
renderTarget.Render(docPage.Visual);
PngBitmapEncoder encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(renderTarget));
FileStream pageOutStream = new FileStream(name + ".Page" + pageNum + ".png", FileMode.Create, FileAccess.Write);
encoder.Save(pageOutStream);
pageOutStream.Close();
This code is taken from http://xpsreader.codeplex.com/ a project to convert an XPS document.
works great!
But the problem is that the image is low resolution and blurry.
I researched and found that RenderTargetBitmap and find on this page:
http://www.codeproject.com/Questions/213737/Render-target-bitmap-quality-issues
The issue here is you Have That does not use hardware RenderTargetBitmap rendering.
One solution is to use DirectX with WPF to do this, but have not found any clear example to show me the right way to do it.
I appreciate suggestions. Thanks in advance.
Update:I attached the XPS document, I am trying to convert the image
Please download test.xps
There is a project named xps2img on sourceforge.net which converts an xps to image. It is made in C# and also contains the source code. Check it out. It will help you to achieve what you want.
http://sourceforge.net/projects/xps2img/files/
I saw in this post and in many others that peoples have problems with conversion of DocumentPage to Image and saving it on HDD.
This method took all pages from document viewer and save them on HDD as jpg images.
public void SaveDocumentPagesToImages(IDocumentPaginatorSource document, string dirPath)
{
if (string.IsNullOrEmpty(dirPath)) return;
if (dirPath[dirPath.Length - 1] != '\\')
dirPath += "\\";
if (!Directory.Exists(dirPath)) return;
MemoryStream[] streams = null;
try
{
int pageCount = document.DocumentPaginator.PageCount;
DocumentPage[] pages = new DocumentPage[pageCount];
for (int i = 0; i < pageCount; i++)
pages[i] = document.DocumentPaginator.GetPage(i);
streams = new MemoryStream[pages.Count()];
for (int i = 0; i < pages.Count(); i++)
{
DocumentPage source = pages[i];
streams[i] = new MemoryStream();
RenderTargetBitmap renderTarget =
new RenderTargetBitmap((int)source.Size.Width,
(int)source.Size.Height,
96, // WPF (Avalon) units are 96dpi based
96,
System.Windows.Media.PixelFormats.Default);
renderTarget.Render(source.Visual);
JpegBitmapEncoder encoder = new JpegBitmapEncoder(); // Choose type here ie: JpegBitmapEncoder, etc
encoder.QualityLevel = 100;
encoder.Frames.Add(BitmapFrame.Create(renderTarget));
encoder.Save(streams[i]);
FileStream file = new FileStream(dirPath + "Page_" + (i+1) + ".jpg", FileMode.CreateNew);
file.Write(streams[i].GetBuffer(), 0, (int)streams[i].Length);
file.Close();
streams[i].Position = 0;
}
}
catch (Exception e1)
{
throw e1;
}
finally
{
if (streams != null)
{
foreach (MemoryStream stream in streams)
{
stream.Close();
stream.Dispose();
}
}
}
}
A nuget package based on xps2img is now available:
https://www.nuget.org/packages/xps2img/
Api available here:
https://github.com/peters/xps2img#usage
private IList<byte[]> GetTifPagesFromXps(string xXpsFileName, double xQuality)
{
using (var xpsDoc = new XpsDocument(xXpsFileName, FileAccess.Read))
{
var docSeq = xpsDoc.GetFixedDocumentSequence();
var tifPages = new List<byte[]>();
for (var i = 0; i < docSeq.DocumentPaginator.PageCount; i++)
{
using (var docPage = docSeq.DocumentPaginator.GetPage(i))
{
var renderTarget = new RenderTargetBitmap((int)(docPage.Size.Width * xQuality), (int)(docPage.Size.Height * xQuality), 96 * xQuality, 96 * xQuality, PixelFormats.Default);
renderTarget.Render(docPage.Visual);
var jpegEncoder = new JpegBitmapEncoder { QualityLevel = 100 };
jpegEncoder.Frames.Add(BitmapFrame.Create(renderTarget));
byte[] buffer;
using (var memoryStream = new MemoryStream())
{
jpegEncoder.Save(memoryStream);
memoryStream.Seek(0, SeekOrigin.Begin);
buffer = memoryStream.GetBuffer();
}
tifPages.Add(buffer);
}
}
xpsDoc.Close();
return tifPages.ToArray();
}
}