Displaying all images from directory - asp.net

I am trying to display images from directory , all images are loading but there are not showing , just a box of size i defined through coding .
First here is my code.
string imagepath = Server.MapPath("~/Images/");
string[] images =Directory.GetFiles(imagepath,"*.png",SearchOption.TopDirectoryOnly);
foreach (string filepath in images)
{
System.Web.UI.WebControls.Image te = new System.Web.UI.WebControls.Image();
te.ImageUrl = filepath;
te.Height = 100;
te.Width = 200;
//Here myimages is my div in which all images will be added.
myimages.Controls.Add(te);
}
Now the screen shot what i am getting .
link below:
http://pages.apunkashaher.com/error.html
So, any one can help out what is missing ?

string imagepath = Server.MapPath("~/Images/");
string[] images =Directory.GetFiles(imagepath,"*.png",SearchOption.TopDirectoryOnly);
foreach (string filepath in images)
{
Image te = new Image();
string fileurl = Path.GetFileName(filepath.ToString());
te.ImageUrl = "~/Images/" + fileurl;
te.Height = 100;
te.Width = 200;
te.CssClass = "zoom";
//Here myimages is my div in which all images will be added.
myimages.Controls.Add(te);
}
Hence Solved & Working.

I'd check what links the images are actually rendering in HTML by viewing the source, I suspect that the code is finding the images but that you are not rendering the correct URL for the browser.

Related

QrCoder Asp.Net - How to remove noise?

Right now I'm creating my QR-Code using QrCoder from Asp.Net. You can see my code below:
SvgQrCode:
public void UpdateText(string value)
{
using (var qrGenerator = new QRCodeGenerator())
{
using (var qrCodeData = qrGenerator.CreateQrCode(value, QRCodeGenerator.ECCLevel.Q))
{
using (var qrCode = new QRCode(qrCodeData))
{
using (var bitmap = qrCode.GetGraphic(1, Color.Black, Color.White, false))
{
Image.FromData(bitmap);
}
Text = value;
} } } }
Xml:
<Image Source="{Binding Element.ImageSource}"
RenderOptions.BitmapScalingMode="NearestNeighbor"
RenderOptions.EdgeMode="Aliased"
Width="{Binding Element.Width}"
Height="{Binding Element.Height}"
Stretch="Uniform">
What happens:
The generated QR-Code has some light noise that you can see here in the screenshot on the left side(left side Gray8, right side BlackWhite):
What I tried:
I changed in the method Decode the Pixelformats from Gray8 to BlackWhite. The result is the screenshot above (qr code on the right side).
internal static BitmapSource Decode(string value, int? pixelWidth, BitmapCacheOption cacheOption = BitmapCacheOption.OnLoad)
{
// ..some code..
var grey = new FormatConvertedBitmap(bitmap, PixelFormats.Gray8, BitmapPalettes.Gray256, 1.0);
return grey;
}
Another thing that I tried is changing qrCode.GetGraphic(1) to something higher like qrCode.GetGraphic(10), which increases the pixels per module. But this is not a clean way to fix the problem, because the noise is just getting realy small(so you can hardly see it anymore) and the pixel per module are getting increased.
My Problem: I'm using the method decode for qr codes, bar codes and images. So If I would add an image it would be black and white. Of course I can use an if-statement and check what if its an image or or qr/bar-code. But why is PixelFormats.Gray8 creating noise? Why is it not clean?
I found the problem. I overlooked those lines and didnt realize that .jpeg was choosen as format:
public void FromData(Bitmap bitmap)
{
using (var ms = new MemoryStream())
{
bitmap.Save(ms, ImageFormat.Jpeg);
//...

Error in displaying image in HTML file

In my MVC2 application I use CKEditor where I allow the user to create a PDF document.
First the CKEditor content will get converted into HTML file and later as PDF document.
I have provided a button called Arrow on click of it image of an arrow should get inserted. In editor image gets displayed successfully but in HTML and PDF file image is not getting displayed inplace of it alt content gets displayed.
Code for an arrow button:
<input type="button" class="green_button" id="arrow" name="Arrow" value="Arrow" style="width: 110px; height: 30px; background-color: #FFFFFF;" onclick="return arrow_onclick()" />
function arrow_onclick() {
var editor = CKEDITOR.instances.message;
editor.insertHtml(' <input type="image" alt="arrow" src="../../PDFimages/arrow-left-up.jpg" style="height:100px; width:100px" />');
}
Controller code:
public ActionResult CreateFile(FormCollection data)
{
var filename = data["filename"];
var htmlContent = data["content"];
string sFilePath = Server.MapPath(_createdPDF + filename + ".html");
htmlContent = htmlContent.Trim();
if (!System.IO.File.Exists(sFilePath))
{
using (FileStream fs = new FileStream(sFilePath, FileMode.Create))
{
using (StreamWriter w = new StreamWriter(fs, Encoding.UTF8))
{
w.Write(htmlContent);
}
}
string filename1 = Path.GetFileNameWithoutExtension(sFilePath);
string name = Server.MapPath(_createdPDF + filename1 + ".pdf");
HTML2PDF.SetModulePath(#"C:\Documents and Settings\shubham\My Documents\visdatemplatemanger\visdatemplatemanger\bin");
using (PDFDoc doc = new PDFDoc())
{
if (HTML2PDF.Convert(doc, sFilePath))
doc.Save(name, pdftron.SDF.SDFDoc.SaveOptions.e_linearized);
}
System.IO.File.Delete(sFilePath);
UploadURL(name);
}
return View();
}
Before submit your form, you should set textarea value from CkEditor and make your action that accepts the post has this annotation applied [HttpPost, ValidateInput(false)]
$("#content").val(CKEDITOR.instances.message.getData());
And check your src value. Maybe should using:
src="#(Url.Content( "~/PDFimages/arrow-left-up.jpg" ))"
if PDFimages folder included in Project/Content

GetImageThumbnail() with dimensions

In our ASP.NET MVC 3 We are currently generating thumbnail images on the fly with the following code:
public void GetImageThumbnail(string imageName)
{
WebImage wbImage = new WebImage("~/assets/images/gallery/"+imageName+".jpg");
int width = 220;
wbImage.Resize(width, (int)((double)wbImage.Height * width / wbImage.Width));
wbImage.FileName = imageName+"_small.jpg";
wbImage.Write();
}
and displaying them in the view like this:
<img src="#Url.Action("GetImageThumbnail", new {imageName = "motherboard"})" alt="" />
How can we control the image size on the view and generate the complete <img> tag from scratch? We need to specify the image dimension and obtain an <img> tag the contains the width and height properties.
Thanks.
My first thought is to create your own HTML helper method which does all of the work. Something you would consume like:
#Html.ThumbnailImg("motherboard")
That method does the thumbnail work and can output the full desired markup. More info: http://www.asp.net/mvc/tutorials/older-versions/views/creating-custom-html-helpers-cs. For what it's worth, I prefer the extension method design. It seems more palatable to other devs.
UPDATE:
There is a little bit of chicken-and-egg that I didn't think about before. Perhaps something like:
public static MvcHtmlString ThumbnailImg(
this HtmlHelper html,
UrlHelper url,
String imageName,
String elementID,
String altText)
{
var img = new TagBuilder("img");
if (String.IsNullOrEmpty(elementID) == false) img.MergeAttribute("id", elementID);
if (String.IsNullOrEmpty(altText) == false) img.MergeAttribute("alt", altText);
// Generate and cache thumnail here, determining height and width
// ...
var src = url.Action("GetImageThumbnail", new { imageName = imageName });
img.MergeAttribute("height", height);
img.MergeAttribute("width", width);
img.MergeAttribute("src", src);
return MvcHtmlString.Create(img.ToString(TagRenderMode.SelfClosing));
}

URL Rewriting and a load images on my pages

I am developing a website in ASP.Net(Forms approach) and rewrite my URL manually in my global.asax file and Application_BeginRequest method
look at this code :
<div style="background-image: url(<%= ResolveUrl("~/Storage/Images/admin-bk.gif") %>);">
I use this way in my aspx file to address images or css files or js files
Problem is here :
I have a gridview(FlexiGrid) and I use Jquery Ajax and call a webmethod to populate the grid.and my web method return html code .In this html code i have some images.
If URL equals to :
http://localhost/Cpanel/BasicDefinitions/Regions
my images load right.But if URl equals to
http://localhost/Cpanel/BasicDefinitions/Regions/
my images do not load.
To solve this problem I need to use ResolveUrl again in my webmethod.But as I know it is impossible to use it in a webmethod.So is there anyone out there to help me handle this error?
This is my webmethod :
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Xml)]
public static string FetchRegionList(int page, int rp, string sortname, string sortorder, string query, string qtype)
{
XDocument xmlDoc = new XDocument(
new XDeclaration("1.0", "utf-8", "yes"),
new XElement("rows",
new XElement("page", page.ToString()),
new XElement("total", RegionBLO.Load().Count.ToString()),
new XElement("row", new XAttribute("Id", row.Id.ToString()),
new XElement("cell", "<img id='imgEdit' lang='" + row.Id.ToString() + #"' style='cursor:pointer;border:0px;' src='"+ ("~/Storage/Images/FlexGrid/edit.png") + "' title='Edit' />
<img id='imgDelete' lang='" + row.Id.ToString() + "' style='cursor:pointer;border:0px;' src='"+ ("~/Storage/Images/FlexGrid/close.png") + "' title='Delete' />")
)
)
);
StringBuilder builder = new StringBuilder();
using (TextWriter writer = new StringWriter(builder))
{
xmlDoc.Save(writer);
}
return builder.ToString();
}
Thanks, Ali
Instead of adding the images as <img> tags, you could add <span> or <a> tags with predefined CSS classes edit and close.
new XElement("cell", "<a ... class='edit'></a><a ... class='delete'></a>")
Then you can use the following CSS to give those elements a background image:
a.edit, a.delete {
display: inline-block;
width: 16px;
height: 16px;
cursor: pointer;
border:0px;
background-repeat: no-repeat;
}
a.edit {
background-image: url(../Images/FlexGrid/edit.png);
}
a.delete {
background-image: url(../Images/FlexGrid/delete.png);
}
The paths to the images from the CSS file are always relative to the CSS file itself. So you don't have to worry about using ResolveUrl server-side, the browser will find the image regardless of the virtual path that the site is running from.
In this case the file locations are:
~/storage/images/edit.png
~/storage/images/delete.png
~/storage/stylesheets/site.css
And so you can see that the path ../Images/FlexGrid/edit.png, when used in the CSS file will point to the image.

using Htmlagility pack to find a div from html string

I have a table where in one column, I have saved all the html of a page. I want to fetch a div( and its contents) from that div using htmlagility how can I do this. I don't want to load it from url or do screen scraping.
// Load your html
HtmlDocument htmlDocument = new HtmlDocument();
htmlDocument.LoadHtml(html);
// Find div with an id or you could use a class if you want
var nodes = htmlDocument.DocumentNode.SelectNodes("//div[#id='myDivId']");
I found this solution.
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(#html);
HtmlNodeCollection tableRows = doc.DocumentNode.SelectNodes("//tr");
string content = "";
if (tableRows.Count > 1)
{
HtmlNode node = doc.DocumentNode.SelectSingleNode("//div[#class='account-detail']");
content = node.InnerHtml;
}
thank you all for your time.

Resources