How do I create an image of a webpage and save the image to my server using .net? - asp.net

I have a page that dynamically generates a small html page containing 1 small table w/text. I want to be able to take a picture (png preferable) of that page and save it to my server.
I was previously using a 3rd party solution (ABCdrawHTML2), but I have changed servers and this one does not have it. Is there a way to do it without 3rd party solutions?

This is how I do it using the Windows.Forms WebBrowser:
public class WebSiteThumbnailImage
{
string m_Url;
int m_BrowserWidth, m_BrowserHeight, m_ThumbnailWidth, m_ThumbnailHeight;
Bitmap m_Bitmap = null;
public WebSiteThumbnailImage(string url, int browserWidth, int browserHeight, int thumbnailWidth, int thumbnailHeight)
{
m_Url = url;
m_BrowserWidth = browserWidth;
m_BrowserHeight = browserHeight;
m_ThumbnailWidth = thumbnailWidth;
m_ThumbnailHeight = thumbnailHeight;
}
public Bitmap GenerateWebSiteThumbnailImage()
{
Thread m_thread = new Thread(new ThreadStart(_GenerateWebSiteThumbnailImage));
m_thread.SetApartmentState(ApartmentState.STA);
m_thread.Start();
m_thread.Join();
return m_Bitmap;
}
private void _GenerateWebSiteThumbnailImage()
{
WebBrowser m_WebBrowser = new WebBrowser();
m_WebBrowser.ScrollBarsEnabled = false;
m_WebBrowser.Navigate(m_Url);
m_WebBrowser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(WebBrowser_DocumentCompleted);
while (m_WebBrowser.ReadyState != WebBrowserReadyState.Complete)
Application.DoEvents();
m_WebBrowser.Dispose();
}
private void WebBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
WebBrowser m_WebBrowser = (WebBrowser)sender;
m_WebBrowser.ClientSize = new Size(this.m_BrowserWidth, this.m_BrowserHeight);
m_WebBrowser.ScrollBarsEnabled = false;
m_Bitmap = new Bitmap(m_WebBrowser.Bounds.Width, m_WebBrowser.Bounds.Height);
m_WebBrowser.BringToFront();
m_WebBrowser.DrawToBitmap(m_Bitmap, m_WebBrowser.Bounds);
m_Bitmap = (Bitmap)m_Bitmap.GetThumbnailImage(m_ThumbnailWidth, m_ThumbnailHeight, null, IntPtr.Zero);
}
}
To use this, at the appropriate place in your code-behind, do something like:
WebSiteThumbnailImage thumbnail = new WebSiteThumbnailImage(url, 1000, 1000, 200, 200);
Bitmap image = thumbnail.GenerateWebSiteThumbnailImage();
image.Save(filePath);

Related

Xamarin.Forms Directory Picker

I would like to save a file in a user selected folder, thats why I would like to provide a directory list to user and user will be able to choose the directory where he wants to export the data. Unfortuntely I could not find any example for directory/folder picker, I just found a file picker which is not useful for me..
https://github.com/jfversluis/FilePicker-Plugin-for-Xamarin-and-Windows
Is there any component for picking a folder for Xamarin.Forms? Actually I am just doing for Android but we use Xamarin.forms
There is none I can think of.
With netstandard everything is way more simple as you can use the classic c# File api to get the folders.
You just have to know the mappings between special folders and android folders (per example):
System.Environment.SpecialFolder Path
ApplicationData INTERNAL_STORAGE/.config
Desktop INTERNAL_STORAGE/Desktop
LocalApplicationData INTERNAL_STORAGE/.local/share
MyDocuments INTERNAL_STORAGE
MyMusic INTERNAL_STORAGE/Music
MyPictures INTERNAL_STORAGE/Pictures
MyVideos INTERNAL_STORAGE/Videos
Personal INTERNAL_STORAGE
source: https://learn.microsoft.com/en-US/xamarin/android/platform/files/
same for ios:
https://learn.microsoft.com/en-US/xamarin/ios/app-fundamentals/file-system
But it's really easy to implement, just enumerate all folders and display them in a ListView.
EDIT: more details on implementation.
In fact you want to code a "directory explorer", it's easy, here is the concept.
You have a ListView in your Page
You have a Cancel button and a Select button in your Page
You have a CurrentPath in your ViewModel
You bind CurrentPath to the Title of your Page
You have an List<DirectoryViewModel> Directories in your ViewModel
Each time a user click on a item from the list:
You add the directory name in your current path
You get all the directories from the new path, and update your Directories property (don't forget RaisePropertyChange(nameof(Directories)))
The ListView will be updated accordingly
Each time you back:
You remove last part of your current path
same as before
If you arrive to root path "/", you do nothing when clicking on back.
Oh and you could use this Grid component to instead of the ListView, will be nicer ;)
https://github.com/roubachof/Sharpnado.Presentation.Forms#grid-Layout
You can edit this to make it work..
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Java.IO;
using Java.Util;
namespace Android.Basic.IO
{
public class DirectoryPicker : ListActivity
{
public const String START_DIR = "startDir";
public const String ONLY_DIRS = "onlyDirs";
public const String SHOW_HIDDEN = "showHidden";
public const String CHOSEN_DIRECTORY = "chosenDir";
public const int PICK_DIRECTORY = 43522;
private File dir;
private Boolean showHidden = false;
private bool onlyDirs = true;
public override void OnCreate(Bundle savedInstanceState, PersistableBundle persistentState)
{
base.OnCreate(savedInstanceState, persistentState);
Bundle extras = Intent.Extras;
dir = OS.Environment.ExternalStorageDirectory;
if (extras != null)
{
String preferredStartDir = extras.GetString(START_DIR);
showHidden = extras.GetBoolean(SHOW_HIDDEN, false);
onlyDirs = extras.GetBoolean(ONLY_DIRS, true);
if (preferredStartDir != null)
{
File startDir = new File(preferredStartDir);
if (startDir.IsDirectory)
{
dir = startDir;
}
}
}
SetContentView(Resource.Layout.folder_chooser_activity);
var title = dir.AbsolutePath.ToString();
Title = (title);
Button btnChoose = (Button)FindViewById(Resource.Id.btnChoose);
String name = dir.Name;
if (name.Length == 0)
name = "/";
btnChoose.Text = ("Choose " + "'" + name + "'");
btnChoose.Click += delegate
{
returnDir(dir.AbsolutePath);
};
ListView lv = this.ListView;
lv.TextFilterEnabled = (true);
if (!dir.CanRead())
{
Context context = ApplicationContext;
String msg = "Could not read folder contents.";
Toast.MakeText(context, msg, ToastLength.Long).Show();
return;
}
var files = filter(dir.ListFiles(), onlyDirs, showHidden);
String[] names = Names(files);
ListAdapter = (new ArrayAdapter<String>(this, Resource.Layout.folder_chooser_item, names));
lv.ItemClick += (ff, gg) =>
{
var position = gg.Position;
if (!files[gg.Position].IsDirectory)
return;
String path = files[position].AbsolutePath;
var intent = new Intent(this, typeof(DirectoryPicker));
intent.PutExtra(DirectoryPicker.START_DIR, path);
intent.PutExtra(DirectoryPicker.SHOW_HIDDEN, showHidden);
intent.PutExtra(DirectoryPicker.ONLY_DIRS, onlyDirs);
StartActivityForResult(intent, PICK_DIRECTORY);
};
}
protected void OnActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == PICK_DIRECTORY && resultCode == (int)Result.Ok)
{
Bundle extras = data.Extras;
String path = (String)extras.Get(DirectoryPicker.CHOSEN_DIRECTORY);
returnDir(path);
}
}
private void returnDir(String path)
{
Intent result = new Intent();
result.PutExtra(CHOSEN_DIRECTORY, path);
SetResult(Result.Ok, result);
Finish();
}
public List<File> filter(File[] file_list, bool onlyDirs, bool showHidden)
{
var files = new List<File>();
foreach (var file in file_list)
{
if (onlyDirs && !file.IsDirectory)
continue;
if (!showHidden && file.IsHidden)
continue;
files.Add(file);
}
Collections.Sort(files);
return files;
}
public String[] Names(List<File> files)
{
String[] names = new String[files.Count];
int i = 0;
foreach (var file in files)
{
names[i] = file.Name;
i++;
}
return names;
}
}
}
Start activity as result then catch in OnActivityResult
if (requestCode == DirectoryPicker.PICK_DIRECTORY && resultCode == Result.Ok)
{
Bundle extras = data.Extras;
String path = (String)extras.Get(DirectoryPicker.CHOSEN_DIRECTORY);
// do stuff with path
}

Report localization in Telerik self hosted service (.trdx)

I have telerik REST web API(ASP.NET ) which is working fine. Now I need to localize the reports (report are in .trdx extension).
From documentation of telerik I found the code which have place in my BaseTelerikReportsController but this also not working, and even not show any error.
Telerik Localization Documentation
public class BaseTelerikReportsController : ReportsControllerBase
{
static readonly Telerik.Reporting.Services.ReportServiceConfiguration ConfigurationInstance;
static BaseTelerikReportsController()
{
var resolver = new CustomReportResolver();
//Create new CultureInfo
var cultureInfo = new System.Globalization.CultureInfo("aa-iq"); //<-- Line 1
// Set the language for static text (i.e. column headings, titles)
System.Threading.Thread.CurrentThread.CurrentUICulture = cultureInfo; //<-- Line 2
var reportsPath = HttpContext.Current.Server.MapPath("~/Reports");
ConfigurationInstance = new Telerik.Reporting.Services.ReportServiceConfiguration
{
HostAppId = "TBReportApp",
ReportResolver = resolver,
// ReportResolver = new ReportFileResolver(reportsPath),
Storage = new Telerik.Reporting.Cache.File.FileStorage(),
};
}
public BaseTelerikReportsController()
{
ReportServiceConfiguration = ConfigurationInstance;
}
}
Note
There is a similar question but don't guide me to any right direction Here
Update 1
I have added below function in Global.asax.cs.
protected void Application_AcquireRequestState(object sender, EventArgs e)
{
//Create new CultureInfo
var cultureInfo = new System.Globalization.CultureInfo("ar");
// Set the language for static text (i.e. column headings, titles)
System.Threading.Thread.CurrentThread.CurrentUICulture = cultureInfo;
// Set the language for dynamic text (i.e. date, time, money)
System.Threading.Thread.CurrentThread.CurrentCulture = cultureInfo;
}
After above line (see image) data under red mark is localize but i need to localize yellow one(i.e heading)
I figure out how to localize the report header. Following are the some summarized steps.
Add App_GlobalResources folder and .resx accordingly your languages (See the figure 1-1).
Send language attribute from 'HTML5 Viewer'.
var viewer = $("#report-viewer").data("telerik_ReportViewer");
var model = {
//other attributes
Language: this.selectedLanguage //Here value may be ,en Or ar
};
viewer.reportSource({
report: reportSettings,
parameters: model
});
On server side based on that attribute change label accordingly.
private static void Localization(ref Report reportInstance)
{
ResourceManager currentResource = null;
switch (_language)
{
case "en":
currentResource = new ResourceManager("Resources.en", System.Reflection.Assembly.Load("App_GlobalResources"));
break;
case "ar":
currentResource = new ResourceManager("Resources.ar", System.Reflection.Assembly.Load("App_GlobalResources"));
break;
}
// var MyResourceClass = new ResourceManager("Resources.ar", System.Reflection.Assembly.Load("App_GlobalResources"));
ResourceSet resourceSet = currentResource.GetResourceSet(CultureInfo.CurrentUICulture, true, true);
foreach (DictionaryEntry entry in resourceSet)
{
string key = entry.Key.ToString();
string value = entry.Value.ToString();
var items = reportInstance.Items.Find(key,true);
foreach (var singleItem in items)
{
var singleItemType = singleItem.GetType();
//if (singleItem.GetType().FullName == "") ;
if (singleItemType.FullName == "Telerik.Reporting.TextBox")
{
var castItem = (Telerik.Reporting.TextBox) singleItem;
castItem.Value = value;
}
}
}
}
On Telerik Standalone Report Designer
Change your report(.trdx) Textbox value which matches your .resxname value pair.
Resource file values

Web Api or Web Service [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I read lots of about Web Api. For example i understand Web Service is a kind of Web Api or Web Api is more flexible.
But i didn't get that: Is Web Api future of Web Service?
For example one of our client needs data from our main database. Normally i use a Web Service for this -simple- purpose but this time i created a Web Api project. I got and service data plus i figured out how it works with Entity or Identity etc. But it's not simple as a web service. I think our client will think same thing also because of identity thing. So why should i prefer Web Api vs Web Service or should i prefer Web Api in this -simple- case?
This kind of depends what you mean by 'web service', but for now I'm going to assume you mean the old .net SOAP services.
If you are building something new today (September 2015) you are almost certainly better off using an asp.net web API. This is a standard REST-style service which can be called by almost any HTTP enabled client with no requirements for local software or understanding of how the service works, this is the whole point of the REST architectural style. I blogged a little about web API and REST here: http://blogs.msdn.com/b/martinkearn/archive/2015/01/05/introduction-to-rest-and-net-web-api.aspx
In your case of a simple service that adds CRUD operations to a database using entity framework. This can be very easily achieved with Web API. You can actually scaffold this whole thing based on a simple model.
To answer your specific question, Yes I believe that in eth asp.net world at least, web API is the future of web services. In fact web services have now been dropped in favour of web API.
Web API supports the .net identity model (I blogged on this here: http://blogs.msdn.com/b/martinkearn/archive/2015/03/25/securing-and-working-securely-with-web-api.aspx) and entity framework.
Hope this helps, if it does please mark as an answer or let me know of any more details you need.
public class Service1 : System.Web.Services.WebService
{
private List<string> GetLines(string filename) {
List<string> lines = new List<string>();
//filename: ime fajla (valute.txt) SA EXT
using (StreamReader sr = new StreamReader(Server.MapPath("podaci/" + filename))) {
string line;
while ((line = sr.ReadLine()) != null) {
lines.Add(line);
}
}
return lines;
}
[WebMethod]
public string HelloWorld()
{
return "Hello World";
}
[WebMethod]
public double ProcitajKursNaDan(DateTime datum, string valuta) {
List<string> podaci = GetLines("valute.txt");
double kurs = 0.0;
// Pronalazenje upisa
for (int i = 0; i < podaci.Count; i++) {
string[] linija = podaci[i].Split('|');
/* Датум[0] | Oznaka valute[1] | Kurs[2] */
string dat = linija[0];
string val = linija[1];
string vrednost = linija[2];
// Uklanjanje viska
dat = dat.Trim();
val = val.Trim();
vrednost = vrednost.Trim();
// Konverzija:
DateTime datIzFajla = DateTime.ParseExact(dat, "d/M/yyyy", null);
double kursIzFajla = Convert.ToDouble(vrednost);
if (DateTime.Compare(datIzFajla, datum) == 0 && val == valuta)
kurs = kursIzFajla;
}
return kurs;
}
[WebMethod]
public bool UpisiKursNaDan(DateTime datum, string valuta, double Kurs) {
string date = datum.ToString("d/M/yyyy");
string linijaZaUpis = date + " | " + valuta + " | " + Kurs.ToString();
bool success = false;
try
{
StreamWriter sw = new StreamWriter(Server.MapPath("podaci/valute.txt"), true);
sw.WriteLine(linijaZaUpis);
sw.Close();
success = true;
}
catch {
success = false;
}
return success;
}
[WebMethod]
public List<string> ProcitajSveValute() {
List<string> linije = GetLines("valute.txt");
List<string> ValuteIzFajla = new List<string>();
for (int i = 0; i < linije.Count; i++) {
string linija = linije[i];
string valuta = linija.Split('|')[1];
valuta = valuta.Trim();
ValuteIzFajla.Add(valuta);
}
List<string> ValuteKraj = ValuteIzFajla.Distinct().ToList();
return ValuteKraj;
}
}
}
//using A10App.localhost;
//namespace A10App
//{
// public partial class pregledkursa : System.Web.UI.Page
// {
// protected void Page_Load(object sender, EventArgs e)
// {
// if (!this.IsPostBack) {
// Service1 servis = new Service1();
// List<string> valute = servis.ProcitajSveValute().ToList();
// for (int i = 0; i < valute.Count; i++)
// DropDownList1.Items.Add(valute[i]);
// }
// }
// protected void Button1_Click(object sender, EventArgs e)
// {
// string datum = TextBox1.Text;
// string valuta = DropDownList1.Text;
// Service1 servis = new Service1();
// double kurs = servis.ProcitajKursNaDan(DateTime.ParseExact(datum, "d/M/yyyy", null), valuta);
// if (kurs != 0.0)
// Label2.Text = kurs.ToString();
// else
// Label2.Text = "Nije pronadjen kurs";
// }
// }
//}
//namespace A10App
//{
// public partial class azuriranjeliste : System.Web.UI.Page
// {
// protected void Page_Load(object sender, EventArgs e)
// {
// if (!this.IsPostBack)
// {
// Service1 servis = new Service1();
// List<string> valute = servis.ProcitajSveValute().ToList();
// for (int i = 0; i < valute.Count; i++)
// DropDownList1.Items.Add(valute[i]);
// }
// }
// protected void Button1_Click(object sender, EventArgs e)
// {
// string datum = TextBox1.Text;
// string valuta = DropDownList1.Text;
// string kurs = TextBox2.Text;
// Service1 servis = new Service1();
// servis.UpisiKursNaDan(DateTime.ParseExact(datum, "d/M/yyyy", null), valuta, Convert.ToDouble(kurs));
// }
// }
//}

Generating a Barcode in c#.net

I am working on a project where i want to generate Bar-code based on an user-ID. I need a code which can generate bar-code and also is encrypted. I have found a few codes but they do not seem very helpful. Thank you in advance for help. i have tried this code but it does not provide me the barcode image.
`private void Page_Load(object sender, System.EventArgs e)
{
// Get the Requested code to be created.
string Code = Request["code"].ToString();
// Multiply the lenght of the code by 40 (just to have enough width)
int w = Code.Length * 40;
// Create a bitmap object of the width that we calculated and height of 100
Bitmap oBitmap = new Bitmap(w,100);
// then create a Graphic object for the bitmap we just created.
Graphics oGraphics = Graphics.FromImage(oBitmap);
// Now create a Font object for the Barcode Font
// (in this case the IDAutomationHC39M) of 18 point size
Font oFont = new Font("IDAutomationHC39M", 18);
// Let's create the Point and Brushes for the barcode
PointF oPoint = new PointF(2f, 2f);
SolidBrush oBrushWrite = new SolidBrush(Color.Black);
SolidBrush oBrush = new SolidBrush(Color.White);
// Now lets create the actual barcode image
// with a rectangle filled with white color
oGraphics.FillRectangle(oBrush, 0, 0, w, 100);
// We have to put prefix and sufix of an asterisk (*),
// in order to be a valid barcode
oGraphics.DrawString("*" + Code + "*", oFont, oBrushWrite, oPoint);
// Then we send the Graphics with the actual barcode
Response.ContentType = "image/jpeg" ;
oBitmap.Save (Response.OutputStream, ImageFormat.Jpeg);
}`
Check out this link it is a simple code 39 barcode display which supports a header and footer, printing, saving, and is pretty well customizable. For the encryption part you will have to encrypt your message before converting it to a barcode.
From the link.
Using the code The code is very simple to use, just plop the control
onto a form and you are ready to start customizing it via the
Properties window or through your code. In addition to the
properties, there are also two public functions of interest: public
void Print() This function will display a print dialog and then print
the contents of the control to the selected printer. public void
SaveImage(string filename) This function will save the contents of the
control to a bitmap image specified by filename.
http://www.codeproject.com/Articles/10344/Barcode-NET-Control
Please try Following Code you have to add "FREE3OF9.TTF" font file in your code
Default.aspx.cs code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Text;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
////GenerateBarCode.GenerateBarCodes("dfdfdf", Label1);
GenerateBarCode();
}
}
private void GenerateBarCode()
{
WSBarcodeGenerator.BarCodeGenerator barCodeGen = new WSBarcodeGenerator.BarCodeGenerator();
int barSize = 30;
System.Byte[] imgBarcode =Code39("123456", barSize, true, "Centralbiz...");
MemoryStream memStream = new MemoryStream(imgBarcode);
Bitmap bitmap = new Bitmap(memStream);
bitmap.Save(memStream, ImageFormat.Png);
var base64Data = Convert.ToBase64String(memStream.ToArray());
imgBar.Attributes.Add("src", "data:image/png;base64," + base64Data);
//Response.Write(bitmap);
//var base64Data = Convert.ToBase64String(memStream.ToArray());
//imgBar.Attributes.Add("src", "png");
}
public byte[] Code39(string code, int barSize, bool showCodeString, string title)
{
Code39 c39 = new Code39();
// Create stream....
MemoryStream ms = new MemoryStream();
c39.FontFamilyName = "Free 3 of 9";
c39.FontFileName = Server.MapPath("FREE3OF9.TTF");
c39.FontSize = barSize;
c39.ShowCodeString = showCodeString;
if (title + "" != "")
c39.Title = title;
Bitmap objBitmap = c39.GenerateBarcode(code);
objBitmap.Save(ms, ImageFormat.Png);
//return bytes....
return ms.GetBuffer();
}
}
public class Code39
{
private const int _itemSepHeight = 3;
SizeF _titleSize = SizeF.Empty;
SizeF _barCodeSize = SizeF.Empty;
SizeF _codeStringSize = SizeF.Empty;
#region Barcode Title
private string _titleString = null;
private Font _titleFont = null;
public string Title
{
get { return _titleString; }
set { _titleString = value; }
}
public Font TitleFont
{
get { return _titleFont; }
set { _titleFont = value; }
}
#endregion
#region Barcode code string
private bool _showCodeString = false;
private Font _codeStringFont = null;
public bool ShowCodeString
{
get { return _showCodeString; }
set { _showCodeString = value; }
}
public Font CodeStringFont
{
get { return _codeStringFont; }
set { _codeStringFont = value; }
}
#endregion
#region Barcode Font
private Font _c39Font = null;
private float _c39FontSize = 12;
private string _c39FontFileName = null;
private string _c39FontFamilyName = null;
public string FontFileName
{
get { return _c39FontFileName; }
set { _c39FontFileName = value; }
}
public string FontFamilyName
{
get { return _c39FontFamilyName; }
set { _c39FontFamilyName = value; }
}
public float FontSize
{
get { return _c39FontSize; }
set { _c39FontSize = value; }
}
private Font Code39Font
{
get
{
if (_c39Font == null)
{
PrivateFontCollection pfc = new PrivateFontCollection();
pfc.AddFontFile(_c39FontFileName);
FontFamily family = new FontFamily(_c39FontFamilyName, pfc);
_c39Font = new Font(family, _c39FontSize);
}
return _c39Font;
}
}
#endregion
public Code39()
{
_titleFont = new Font("Arial", 10);
_codeStringFont = new Font("Arial", 10);
}
#region Barcode Generation
public Bitmap GenerateBarcode(string barCode)
{
int bcodeWidth = 0;
int bcodeHeight = 0;
// Get the image container...
Bitmap bcodeBitmap = CreateImageContainer(barCode, ref bcodeWidth, ref bcodeHeight);
Graphics objGraphics = Graphics.FromImage(bcodeBitmap);
// Fill the background
objGraphics.FillRectangle(new SolidBrush(Color.White), new Rectangle(0, 0, bcodeWidth, bcodeHeight));
int vpos = 0;
// Draw the title string
if (_titleString != null)
{
objGraphics.DrawString(_titleString, _titleFont, new SolidBrush(Color.Black), XCentered((int)_titleSize.Width, bcodeWidth), vpos);
vpos += (((int)_titleSize.Height) + _itemSepHeight);
}
// Draw the barcode
objGraphics.DrawString(barCode, Code39Font, new SolidBrush(Color.Black), XCentered((int)_barCodeSize.Width, bcodeWidth), vpos);
// Draw the barcode string
if (_showCodeString)
{
vpos += (((int)_barCodeSize.Height));
objGraphics.DrawString(barCode, _codeStringFont, new SolidBrush(Color.Black), XCentered((int)_codeStringSize.Width, bcodeWidth), vpos);
}
// return the image...
return bcodeBitmap;
}
private Bitmap CreateImageContainer(string barCode, ref int bcodeWidth, ref int bcodeHeight)
{
Graphics objGraphics;
// Create a temporary bitmap...
Bitmap tmpBitmap = new Bitmap(1, 1, PixelFormat.Format32bppArgb);
objGraphics = Graphics.FromImage(tmpBitmap);
// calculate size of the barcode items...
if (_titleString != null)
{
_titleSize = objGraphics.MeasureString(_titleString, _titleFont);
bcodeWidth = (int)_titleSize.Width;
bcodeHeight = (int)_titleSize.Height + _itemSepHeight;
}
_barCodeSize = objGraphics.MeasureString(barCode, Code39Font);
bcodeWidth = Max(bcodeWidth, (int)_barCodeSize.Width);
bcodeHeight += (int)_barCodeSize.Height;
if (_showCodeString)
{
_codeStringSize = objGraphics.MeasureString(barCode, _codeStringFont);
bcodeWidth = Max(bcodeWidth, (int)_codeStringSize.Width);
bcodeHeight += (_itemSepHeight + (int)_codeStringSize.Height);
}
// dispose temporary objects...
objGraphics.Dispose();
tmpBitmap.Dispose();
return (new Bitmap(bcodeWidth, bcodeHeight, PixelFormat.Format32bppArgb));
}
#endregion
#region Auxiliary Methods
private int Max(int v1, int v2)
{
return (v1 > v2 ? v1 : v2);
}
private int XCentered(int localWidth, int globalWidth)
{
return ((globalWidth - localWidth) / 2);
}
#endregion
}
Default.aspx code
<%# Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
CodeFile="Default.aspx.cs" Inherits="_Default" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<h2>
Welcome to ASP.NET!
</h2>
<p>
To learn more about ASP.NET visit www.asp.net.
</p>
<p>
You can also find <a href="http://go.microsoft.com/fwlink/?LinkID=152368&clcid=0x409"
title="MSDN ASP.NET Docs">documentation on ASP.NET at MSDN</a>.
</p>
<asp:Image ID="imgBar" runat="server" />
</asp:Content>

download generated images automatically multiple times

I am trying to download around 1000 images. For that first I am generating random number, converting this text to image. After this on button click, I am downloading this generated image. This is working fine. Now I want to run this loop for 1000 times so that I can download thousand images. The below code works fine when the loop is running once, but when the loop is running 1000 times, its not working as I am expecting.
Also, I want to change the destination folder where this images should be downloaded. How can I do that?
Below if I change value of variable i to 1000, the output is not what I am expecting
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
for (int i = 0; i < 1; i++)
{
CallBUttonClick();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
var s = GenerateRandomCode();
RandomImage ci = new RandomImage(s.ToString(), 300, 75);
this.Response.Clear();
this.Response.ContentType = "image/jpeg";
Response.AppendHeader("Content-Disposition", "attachment; filename=downloadedFile.JPG");
ci.Image.Save(this.Response.OutputStream, ImageFormat.Jpeg);
ci.Dispose();
}
protected void CallBUttonClick()
{
Button1_Click(Button1, null);
}
private string GenerateRandomCode()
{
Random r = new Random();
string s = "";
for (int j = 0; j < 5; j++)
{
int i = r.Next(3);
int ch;
switch (i)
{
case 1:
ch = r.Next(0, 9);
s = s + ch.ToString();
break;
case 2:
ch = r.Next(65, 90);
s = s + Convert.ToChar(ch).ToString();
break;
case 3:
ch = r.Next(97, 122);
s = s + Convert.ToChar(ch).ToString();
break;
default:
ch = r.Next(97, 122);
s = s + Convert.ToChar(ch).ToString();
break;
}
r.NextDouble();
r.Next(100, 1999);
}
return s;
}
}
Adding RandomImage.cs class file
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Drawing.Text;
using System;
public class RandomImage
{
//Default Constructor
public RandomImage() { }
//property
public string Text
{
get { return this.text; }
}
public Bitmap Image
{
get { return this.image; }
}
public int Width
{
get { return this.width; }
}
public int Height
{
get { return this.height; }
}
//Private variable
private string text;
private int width;
private int height;
private Bitmap image;
private Random random = new Random();
//Methods declaration
public RandomImage(string s, int width, int height)
{
this.text = s;
this.SetDimensions(width, height);
this.GenerateImage();
}
public void Dispose()
{
GC.SuppressFinalize(this);
this.Dispose(true);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
this.image.Dispose();
}
private void SetDimensions(int width, int height)
{
if (width <= 0)
throw new ArgumentOutOfRangeException("width", width,
"Argument out of range, must be greater than zero.");
if (height <= 0)
throw new ArgumentOutOfRangeException("height", height,
"Argument out of range, must be greater than zero.");
this.width = width;
this.height = height;
}
private void GenerateImage()
{
Bitmap bmp = new Bitmap(1, 1);
Graphics graphics = Graphics.FromImage(bmp);
Font font = new Font(FontFamily.GenericSansSerif, 28);
SizeF stringSize = graphics.MeasureString(this.text, font);
bmp = new Bitmap(bmp, (int)stringSize.Width+30, (int)stringSize.Height+30);
graphics = Graphics.FromImage(bmp);
graphics.DrawString(this.text, font, Brushes.White, 0, 0);
font.Dispose();
graphics.Flush();
graphics.Dispose();
this.image = bmp;
}
}
Hi you need to save you bitmap file on physcial folder. I have modified you code. Please see below code
private void GenerateImage()
{
Bitmap bmp = new Bitmap(1, 1);
Graphics graphics = Graphics.FromImage(bmp);
Font font = new Font(FontFamily.GenericSansSerif, 28);
SizeF stringSize = graphics.MeasureString(this.text, font);
bmp = new Bitmap(bmp, (int)stringSize.Width + 30, (int)stringSize.Height + 30);
graphics = Graphics.FromImage(bmp);
graphics.DrawString(this.text, font, Brushes.White, 0, 0);
font.Dispose();
graphics.Flush();
graphics.Dispose();
bmp.Save("C:\\" + this.text + ".jpg");
this.image = bmp;
}
I have also removed below code from button click and rested, it is working fine.
//this.Response.Clear();
//this.Response.ContentType = "image/jpeg";
//Response.AppendHeader("Content-Disposition", "attachment; filename=downloadedFile.JPG");
//ci.Image.Save(this.Response.OutputStream, ImageFormat.Jpeg);
//ci.Dispose();
That's not how the ASP.NET Page Life Cycle works. If you use the Response object to serve a download, you can serve ONE file.
You are approaching the problem from the wrong side; you say "I am trying to download around 1000 images". That is a process on the client side, on the browser if you will.
Yet you are trying to solve this on the server side.
You want 1000 downloads, so you have to initiate 1000 downloads from the client, and let the server side, the one Page you're writing for that, live through that 1000 times.
In other words, you cannot "push download" multiple files from the server, you have to request them one by one.

Resources