Image.ImageUrl = ... nothing is displayed - c#

On my development system (Win 10 Pro, VS 2015), I am testing a web forms app in VS 2015; it uses a master page. An image control in an asp content page shows nothing when I try to display a photo from a file just written after a resize, whereas it displays the original photo just fine. Here is the code-behind fragment with the problem detailed in the comments:
// During testing, sRelLoc contains "~/i/SlideShow/1th.jpg" (original photo)
string sRelLocMod = sRelLoc.Replace("~/", "").Replace("/", "\\");
// During testing, Global.sgHomeDir contains "K:\\DataAndDocs\\12_Projects\\TinyNP\\TinyNP\\"
string sImgUrl = Global.sgHomeDir + sRelLocMod;
// sImgUrl now contains
System.Drawing.Image Photo = null;
// Read original photo from file
using (FileStream fs = new FileStream(sImgUrl, FileMode.Open, FileAccess.Read))
{
Photo= System.Drawing.Image.FromStream(fs);
}
// ResizeImage from https://www.codeproject.com/articles/191424/resizing-an-image-on-the-fly-using-net
System.Drawing.Image PhotoResized = ResizeImage(Photo, new Size(400, 400), true);
sImgUrl = Global.sgHomeDir + "i\\tempImg.jpg";
using (FileStream fs = new FileStream(sImgUrl, FileMode.Open, FileAccess.Write))
{
PhotoResized.Save(fs,System.Drawing.Imaging.ImageFormat.Jpeg);
}
// NOTE THAT: The image has been saved correctly in its resized form inside the expected directory
sImgUrl = sImgUrl.Replace("\\", "/");
//sImgUrl now contains "K:/DataAndDocs/12_Projects/TinyNP/TinyNP/i/tempImg.jpg"
// Image1 is an Image control on an asp.net web page.
// PROBLEM: The following statement displays nothing where Image1 is
// placed (not even a red-x or anything) , ...
Image1.ImageUrl = sImgUrl;
// ... but displays the unresized original just fine when the following statement is used instead:
// Image1.ImageUrl = sRelLoc;
Same behavior whether or not running in debug mode.
Perhaps there is a better approach than writing the resized photo to temporary file tempImg.jpg and then reading from it?
Update after jignesh's and Sami's responses:
I am using MapPath in Default.aspx.cs (see new comments below).
Now using System.Uri to convert path to Url which starts with "file:///". Leads to nothing being displayed. Replacing "file:" with "http:" leads to a broken image symbol being displayed. Updated code is:
// During testing, sRelLoc contains "~/i/SlideShow/1.jpg" (original photo)
string sRelLocMod = sRelLoc.Replace("~/", "").Replace("/", "\\");
// During testing, Global.sgHomeDir contains "K:\\DataAndDocs\\12_Projects\\TinyNP\\TinyNP"
// which was obtained in Default.aspx.cs Page Load Event by
// Global.sgHomeDir = HttpContext.Current.Server.MapPath(null);
string sImgPath = Global.sgHomeDir + "\\" + sRelLocMod;
// sImgPath now contains "K:\\DataAndDocs\\12_Projects\\TinyNP\\TinyNP\\i\\SlideShow\\1.jpg"
System.Drawing.Image Photo = null;
// Read original photo from file
using (FileStream fs = new FileStream(sImgPath, FileMode.Open, FileAccess.Read))
{ Photo= System.Drawing.Image.FromStream(fs); }
// ResizeImage from https://www.codeproject.com/articles/191424/resizing-an-image-on-the-fly-using-net
System.Drawing.Image PhotoResized = ResizeImage(Photo, new Size(400, 400), true);
sImgPath = Global.sgHomeDir + "\\i\\tempImg.jpg";
// sImgPath now contains "K:\\DataAndDocs\\12_Projects\\TinyNP\\TinyNP\\i\\tempImg.jpg"
using (FileStream fs = new FileStream(sImgPath, FileMode.OpenOrCreate, FileAccess.Write))
{ PhotoResized.Save(fs, System.Drawing.Imaging.ImageFormat.Jpeg); }
// I have verified that the image has been saved correctly in its resized form inside the expected directory
System.Uri ImgUrl = new System.Uri(sImgPath, UriKind.Absolute);
// Image1 is an Image control on an asp.net web page.
string sImgUrl = ImgUrl.ToString();
//sImgUrl now contains "file:///K:/DataAndDocs/12_Projects/TinyNP/TinyNP/i/tempImg.jpg"
Image1.ImageUrl = sImgUrl;
// The above statement DOES NOT work (displays nothing at all)
// However:
//Image1.ImageUrl = "~/i/tempImg.jpg"; // ** DOES ** work ok
// If I replace "file:" with "http:", a broken image symbol is displayed.
But what does work is using a tilde "~" even though it does not look like a Url. Is it ok to use the tilde? Will it get me into any trouble, like when deploying to a hosting server?

Use the ImageUrl property to specify the URL of an image to display in the Image control.You can use a relative or an absolute URL. A relative URL relates the location of the image to the location of the Web page without specifying a complete path on the server. The path is relative to the location of the Web page. This makes it easier to move the entire site to another directory on the server without updating the code. An absolute URL provides the complete path, so moving the site to another directory requires that you update the code.
By absolute url, they mean the entire IIS path to the URL (Not your disk directory path). (i.e. http://yourVirtualDirectory/ExternalImages/logo.jpg).
So here in above code sImgUrl="K:/DataAndDocs/12_Projects/TinyNP/TinyNP/i/tempImg.jpg" it should be like http://yourVirtualDirectory/tempImg.jpg

Related

How do you save and preview an HTML file from temp folder?

I'm developing an HTML editor in C# where you can edit your code in the FastColoredTextBox.dll component. You will have this option in the MenuStrip called "Preview in browser" and there will be a drop down item called "Chrome" and "Iexplore" etc. I want it instead of saving the file, i want it to make a file in the Temp folder and preview it. and after we've modified the code again, the file will update as we preview it again. This is what i have so far:
string location = null;
string sourcecode = FastColoredTextBox1.Text;
location = System.IO.Path.GetTempPath() + "\\TempSite.html";
using (StreamWriter writer = new StreamWriter(location, true))
{
writer.Write(sourcecode);
writer.Dispose();
}
try
{
System.Diagnostics.Process.Start("chrome.exe", location);
}
catch (Exception ex)
{
Interaction.MsgBox(ex.Message);
}
How do you achieve this?
Q: How do you save and preview an HTML file from temp folder?
A: You're already doing precisely that :)
Q: Why does my browser keep re-displaying the original image?
A: Because your browser is reading the html from cache.
SOLUTION:
Give your new file a different name. For example:
location = System.IO.Path.GetTempPath() + Path.GetTempFileName() + ".html";
... OR ...
location = Path.GetTempPath() + Guid.NewGuid().ToString() + ".html";
You can also simply hit <F5> to refresh, <Ctl-Shift-Del> to clear cache, or disable cache in your browser.

Using a Resource Image as the value in RDLC Parameter

I'm trying to pass an image as a parameter to an Image in a RDLC Report. I tried using the following:
string imgPath = new Uri("pack://application:,,,/Resources/default_product_img.png").AbsoluteUri;
string imgPath = new Uri(AppDomain.CurrentDomain.BaseDirectory + "pack://application:,,,/Resources/default_product_img.png").AbsoluteUri;
string imgPath = new Uri("/Resources/default_product_img.png").AbsoluteUri;
string imgPath = new Uri(AppDomain.CurrentDomain.BaseDirectory + "/Resources/default_product_img.png").AbsoluteUri;
string imgPath = new Uri("pack://application:,,,/Resources/default_product_img.png", UriKind.Absolute).AbsoluteUri;
string imgPath = new Uri(HttpContext.Current.Server.MapPath("~/Resources/default_product_img.png")).AbsoluteUri;
string imgPath = new Uri(HostingEnvironment.MapPath("~/Resources/default_product_img.png")).AbsoluteUri;
but the display always show the red X when I run it. I managed to make this work, but the source of the image is in the same level as the .exe and not inside it.
I also tried creating a BitmapImage, but ReportParameter() only accepts strings.
Is there a way for this to work? Or should I just copy it beside the .exe file?
Things to Note:
The image source is set as External
default_product_img.png is inside Resources folder and has a Build Action of Resource
The parameter name is set as the value in Use this image:
Take the image as a bitmap and save it to a memory stream then convert the memory stream into a base64 string. Pass this string into the parameter and use that parameter as the image. In the RDLC set the image source to be database and make sure the mime type is a correct match for how you saved the bitmap to the memory stream.
string paramValue;
using (var b = new Bitmap("file path or new properties for bitmap")) {
using (var ms = new MemoryStream()) {
b.save(ms, ImageFormat.Png);
paramValue = ConvertToBase64String(ms.ToArray());
}
}
Or if you want to keep it as an external file set the image source to be external in the rdlc and pass the path to the image as file://c:\site\resources\default_product_img.png it will need to be an absolute path and you can use Server.MapPath to convert the web relative path to an absolute local path then just make sure you have file:// at the beginning of the path so the report engine knows it's a local path.

Add downloaded images to resource folder

I have downloaded an image with the following code:
bool pageExists = false;
// Check if webpage exists
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://image.tmdb.org/t/p/w780" + imagePath);
request.Method = WebRequestMethods.Http.Head;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
pageExists = response.StatusCode == HttpStatusCode.OK;
}
// Download image
if (pageExists)
{
string localFilename = #"C:\Users\Giri\Desktop\giri" + id + ".jpg";
using (WebClient client = new WebClient())
{
client.DownloadFile("http://image.tmdb.org/t/p/w780" + imagePath, localFilename);
}
}
For now, I have just been saving this image on my Desktop.
My question is how do I go about storing this image in my WPF application programmatically within a resources folder or a folder I have generated myself? The images should persist in that the next time the application is run, the added images should remain.
Is there an accepted place I should be storing my images?
Thanks for your help.
Please use AppDomain.CurrentDomain.BaseDirectory. Which will give you the directory of your executable. Even in deployed code this should give you the right value. But other values like Environment.CurrentDirectory can give different value based on from where you are calling it etc.
See this question Best way to get application folder path

How to select specific images and save from a particular url? (Description Inside)

I need to select and save some specific images from a site by entering the url in the textbox in my site.
I've loaded all the images from a site url, by using html agility. but now I don't know how to select and save.
For example, I enter http://flipkart.com/ in my text box, it should load all images from that page, assume it contains 9 images, if 9 images loaded from a site and displayed as a gallery, from that gallery I will select 1 image click save. it should save somewhere in my site(may be a particular folder).
I don't know how to save images from a site.
would somebody give some reference or ideas to achieve this task of saving the image that is loaded when a url is given.
Thanks!
string imageUri = "http://www.contoso.com/library/homepage/images/";
string fileName = "ms-banner.gif", myStringWebResource = null;
// Create a new WebClient instance.
WebClient myWebClient = new WebClient();
// Concatenate the domain with the Web resource filename.
myStringWebResource = remoteUri + fileName;
Console.WriteLine("Downloading File \"{0}\" from \"{1}\" .......\n\n", fileName, myStringWebResource);
// Download the Web resource and save it into the current filesystem folder.
myWebClient.DownloadFile(myStringWebResource,fileName);
Console.WriteLine("Successfully Downloaded File \"{0}\" from \"{1}\"", fileName, myStringWebResource);
In myStringWebResource you will mention the path to you folder. I assume you are doing it from the same website on which you want to save the image
EDIT:
I've seen that, but can we use a webclient to load all images from a site. for example if I gave flipkart.com, will it display all images in that page. – Gopinath Perumal
First you need to get the html as string from web client
Then you need to find all the uri in th string which ends with .jpg, .jpeg, .png, .gif etc etc
Iterate the webclient and download each image
But beware, programatically crawling like this is not permitted by many site.
I googled about this and got the below code,
public System.Drawing.Image DownloadImageFromUrl(string imageUrl)
{
System.Drawing.Image image = null;
try
{
System.Net.HttpWebRequest webRequest = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(imageUrl);
webRequest.AllowWriteStreamBuffering = true;
webRequest.Timeout = 30000;
System.Net.WebResponse webResponse = webRequest.GetResponse();
System.IO.Stream stream = webResponse.GetResponseStream();
image = System.Drawing.Image.FromStream(stream);
webResponse.Close();
}
catch (Exception ex)
{
return null;
}
return image;
}
u use this code and save this as an image of desired format.
while saving the image you should mention the Folder/destination path.

Automate WebBrowser.ShowSaveAsDialog() or alternative method

Basically I wan't to save an image loaded in a webBrowser control. The only way I can get this to work at the moment is by showing the save as dialog.
is there a way to pass in a path and make it save itself? (hide the dialog I ask to show!)
is there another way to save the image? I can't seem to get documentstream to work. I have also tried webclient.filedownload(...) but get an error 302 ( "(302) Found Redirect.")
DownloadFileAsync gives no error but an empty jpeg file?
files are always jpegs, but not always at same location.
You should go with HttpWebRequest.
It has the capability to follow a 302 automatically.
var myHttpWebRequest = (HttpWebRequest)WebRequest.Create("http://www.contoso.com");
//increase this number if there are more then one redirects.
myHttpWebRequest.MaximumAutomaticRedirections = 1;
myHttpWebRequest.AllowAutoRedirect = true;
var myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
var buff = new byte[myHttpWebResponse.ContentLength];
// here you specify the path to the file. The path in this example is : image.jpg
// if you want to store it in the application root use:
// AppDomain.CurrentDomain.BaseDirectory + "\\image.jpg"
using (var sw = new BinaryWriter(File.Open("c:\\image.jpg", FileMode.OpenOrCreate)))
{
using (var br = new BinaryReader (myHttpWebResponse.GetResponseStream ()))
{
br.Read(buff, 0, (int)myHttpWebResponse.ContentLength);
sw.Write(buff);
}
}

Categories

Resources