how to take image from physical path(local disc) - c#

filename = Path.GetFileName(FileUpload.FileName);
HttpPostedFile pf = FileUpload.PostedFile;
System.Drawing.Image img2 = System.Drawing.Image.FromStream(pf.InputStream);
System.Drawing.Image bmp2 = img2.GetThumbnailImage(200, 210, null, IntPtr.Zero);
Imagename = objUser.UserID + filename;
Imagepath = "D:\\Shopy_Web_21-6-12\\Shopy\\Images" + Imagename;
bmp2.Save(Path.Combine(#"D:\Shopy_Web_21-6-12\Shopy\Images", Imagename));
I've converted the file upload in to two thumbnails and saved them locally, but now I need retrieve the image to display it on the user's profile. How can I get the image to display from where I've stored it?

You can create a virtual path in your application say: ..Images/ and save your images in that folder.
and after that use the below one to fetch the image URL:
string str = Server.MapPath("Images/" + Filename);
Now you will get the url to your image that can be displayed directly.

Link your images folder (...\Shopy\Images) to a virtual folder under your app so then you can link to them within <img> elements.

Related

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.

How to set path for images to display it through name with different sequences for executable

I'm trying animate 4 images with different sequences, so I'm wondering how to set path to display images with name and also use this path for executable. Question is, where I have to save pictures folder, and how to get path to display images with different sequences through variable name for excusable file to make it available for other users and do not do it that way:
Bitmap img1, img2, img3, img4;
img1 = new Bitmap(#"D:\my_doc\folder\images\1.png", true);
img2 = new Bitmap(#"D:\my_doc\folder\images\2.png", true);
img3 = new Bitmap(#"D:\my_doc\folder\images\3.png", true);
img4 = new Bitmap(#"D:\my_doc\folder\images\4.png", true);
pictureBox1.Image = img1;
Follow this article to add your images to project resources.
After adding the images you can write some codes like this:
System.Drawing.Bitmap img1, img2, img3, img4;
img1 = YourProjectsBaseNamespace.Properties.Resources.img1
img2 = YourProjectsBaseNamespace.Properties.Resources.img2
img3 = YourProjectsBaseNamespace.Properties.Resources.img3
img4 = YourProjectsBaseNamespace.Properties.Resources.img4

ImageResizer - Save Image as a Larger Size

I am trying to use the .net ImageResizer to save an image to a specified size. I am unable to save a smaller image to larger dimensions with the current code I am using. For example, I upload an image that is 200x200, the _thumb version will be saved as 100x100 but the _medium and _large versions will still be 200x200.
How can I save the uploaded image to the specified larger images? Such as versions.Add("_extraLarge", "width=2000&height=2000&crop=auto&format=jpg"); or versions.Add("_XXL", "width=auto&height=3000&crop=auto&format=jpg");
//GenerateVersions(FileUpload1.PostedFile.FileName);
Dictionary<string, string> versions = new Dictionary<string, string>();
//Define the versions to generate
versions.Add("_thumb", "width=100&height=100&crop=auto&format=jpg"); //Crop to square thumbnail
versions.Add("_medium", "maxwidth=400&maxheight=400&format=jpg"); //Fit inside 400x400 area, jpeg
versions.Add("_large", "maxwidth=1900&maxheight=1900&format=jpg"); //Fit inside 1900x1200 area
//Loop through each uploaded file
foreach (string fileKey in HttpContext.Current.Request.Files.Keys)
{
HttpPostedFile file = HttpContext.Current.Request.Files[fileKey];
if (file.ContentLength <= 0) continue; //Skip unused file controls.
//Get the physical path for the uploads folder and make sure it exists
string uploadFolder = MapPath("~/uploadsAIM");
if (!Directory.Exists(uploadFolder)) Directory.CreateDirectory(uploadFolder);
//Generate each version
foreach (string suffix in versions.Keys)
{
////Generate a filename (GUIDs are best).
//string fileName = Path.Combine(uploadFolder, System.Guid.NewGuid().ToString() + suffix);
string fileName = Path.Combine(uploadFolder, file.FileName + suffix);
//Let the image builder add the correct extension based on the output file type
//fileName = ImageBuilder.Current.Build(file, fileName, new ResizeSettings(versions[suffix]), false, true); //deprecated fileName
fileName = ImageBuilder.Current.Build(new ImageJob(file, fileName, new Instructions(versions[suffix]), false, true)).FinalPath;
}
}
By default the scaling mode is set to DownscaleOnly. Set the Scale on the instructions to either up or both depending on your need.
Just note that upscaling an image tends to create blurry images.

how to display image using imageurl in C#

if (FileUpload1.HasFile)
{
string FileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
//string path = Server.MapPath(#"~\\"+Session["parentfolder"].ToString() +"\\"+ Session["brandname"].ToString() + "\\" + Seasonfolders.SelectedItem.Text + "\\" + stylefolders.SelectedItem.Text + "\\Images\\" + FileName);
string root = Server.MapPath("~");
string path = Path.GetDirectoryName(root);
string path1 = Path.GetDirectoryName(path);
string rootfolder = Path.GetDirectoryName(path1);
string imagepath = rootfolder + Session["brandname"].ToString() + "\\" + Seasonfolders.SelectedItem.Text + "\\" + stylefolders.SelectedItem.Text + "\\Images\\" + FileName;
FileUpload1.SaveAs(imagepath);
//objBAL.SaveImage("Image", Session["brandname"].ToString(), Seasonfolders.SelectedItem.Text, stylefolders.SelectedItem.Text, FileName, imagepath, Convert.ToInt32(Session["Empcode"]));
uploadedimage.ImageUrl = Server.MapPath(#"~/"+imagepath);
uploadedimage.DataBind();
}
uploadedimage is ID for Image control. The path of imagepath is E:\Folder1\Folder2\Folder3\Images\1.png
The image is getting saved but I cannot able to display the uploaded image. Do I need to add anything in this line which is to display an image ..
uploadedimage.ImageUrl = Server.MapPath(#"~/"+imagepath);
uploadedimage.DataBind();
Hosting websites or stuff on iis, does not work this way. There are a few concepts one needs to learn on that front, but the best place to start with is understand what is virtual directory.
One quote from the this page:
In IIS 7, each application must have a virtual directory, known as the
root virtual directory, and maps the application to the physical
directory that contains the application's content
So it means this is a directory where the application's "content" reside; it could be simple text files, images, etc, to complex server side pages like aspx or even classic asp, or php, etc. Now anything out of this directory is not accessible by the hosted web application.
Hence the path you intend to share doesn't work that way. There are a few options to handle this scenario.
In iis you could create a sub-virtual directory, and map its path to where your images are stored to the physical location where the images reside.
Provided your web application (when hosted on iis) has access to the path where the images reside, you can write code to read the file, and send the stream of bytes back so that your web page can render image properly.
2nd approach is usually implemented by a handler (ashx) via which you can pass the image name as query string argument, and return the bytes. Hence in short you do something like this:
uploadedImage.ImageUrl = "~/MyImageHandler.ashx?filename=foo.png" //in ur server code.
In the handler you write something like this:
public class MyImageHandler : IHttpHandler {
public void ProcessRequest (HttpContext context) {
// Comment out these lines first:
// context.Response.ContentType = "text/plain";
// context.Response.Write("Hello World");
context.Response.ContentType = "image/png";
var filepath = #"E:\your_image_dir\" + Request.QueryString["filename"];
//Ensure you have permissions else the below line will throw exception.
context.Response.WriteFile(filepath);
}
public bool IsReusable {
get {
return false;
}
}
}
The image Url in your image should be like this
"~/"+ imagepath
Try removing Server.MapPath
Try this
Create Data Folder in your root directory
if (FileUpload1.HasFile)
{
string FileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
string imagepath =Server.MapPath("~/Data/"+FileName);
FileUpload1.SaveAs(imagepath);
uploadedimage.ImageUrl="~/"+imagepath;
}

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.

Categories

Resources