load image after upload in asp.net 4.0 - asp.net

My question is image uploading , uploading and image load method are working perfect but im showing images below the upload control, after click upload button new image must be added to line.. what is the reason?
this is uploading code:
DirectoryInfo directoryInfo = new DirectoryInfo(Server.MapPath(#"~/Bailiffs/BailiffImages/"));
string cukurNumber = txtCukurNumber.Text;
int sequence = 0;
string fileName = string.Empty;
FileInfo[] fileInfos = directoryInfo.GetFiles(cukurNumber + "*");
if (afuImage.HasFile)
{
if (fileInfos.Length != 0)
{
for (int i = 0; i < fileInfos.Length; i++)
{
string fileNumber = fileInfos[i].Name.Substring(fileInfos[i].Name.LastIndexOf("-") + 1, fileInfos[i].Name.LastIndexOf(".") - fileInfos[i].Name.LastIndexOf("-") - 1);
sequence = int.Parse(fileNumber) + 1;
}
fileName = cukurNumber + "--" + sequence + ".jpg";
}
else
{
fileName = cukurNumber + "--1.jpg";
}
afuImage.PostedFile.SaveAs(Server.MapPath(#"/Bailiffs/BailiffImages/" + fileName));
CreateImages(); // recreates images
}
thx...

Use ajax to call a page method which retrieves the url of the image just uploaded and shows it in an img tag. Ajax and Jquery are your tools and friends.

Related

How to save image in to folder or directory in ASP.NET

I have A image like this
imgScreenShot.ImageUrl = "data:image/png;base64," + Convert.ToBase64String(bytes);
instead of binding image to that imgScreenShot i have to save that in to either any folder in project or any directory please help me.
I believe you are trying to convert base64 image string to image.
Below is the code you can use to convert it to image :
public static Image LoadImage(string base64string)
{
byte[] bytes = Convert.FromBase64String(base64string); //Convert.FromBase64String("R0lGODlhAQABAIAAAAAAAAAAACH5BAAAAAAALAAAAAABAAEAAAICTAEAOw==");
Image image;
using (MemoryStream ms = new MemoryStream(bytes))
{
image = Image.FromStream(ms);
}
return image;
}
You can then save image as follows :
Image image = UtilityHelper.LoadImage(ch.Message);
string imgname = ch.MobileNo + "_" + DateTime.UtcNow.ToString("yyyyMMddHHmmssfff") + ".jpg";
string filepath = Path.Combine(System.Web.Hosting.HostingEnvironment.MapPath("~\\Images\\") + subPath + "\\" + imgname);
var image2 = new Bitmap(image);
image2.Save(filepath, ImageFormat.Jpeg);

Create image of Html code with c#

I have created html code and then save this html page as an image . The html controls which I have created is showing properly in the image with all images and background color. It is woking fine on localhost.
but I am trying to creating html code to image on the server. the image is creating but it's not showing anything like bgcolor, images, etc.
only blank image is showing.
Code :
Using Ajax calling function from client side I am sending the html content to the serverside
Server Side Method
[System.Web.Services.WebMethod()]
public static void GenerateTemplateImage(string html_Content, string TemplateName)
{
var t = new Thread(MakeScreenshot);
t.SetApartmentState(ApartmentState.STA);
t.Start();
}
public static void MakeScreenshot()
{
Bitmap bitmap;
string html = string.Empty;
string Title = string.Empty;
string Meta = string.Empty;
string Style = string.Empty;
string ScriptBefore = string.Empty;
string ScriptAfter = string.Empty;
string Scripthead = string.Empty;
html="<div><div id='s_p_box-1' style='background-color: rgb(24, 0, 238); width: 109px; height: 75px;>Welcome </div>' <br/> <img id='template1' class='template' style='border:1px solid green; height:142px;width:116px' src='http://ace.demos.classicinformatics.com/Advertiser-Admin/Campaign/UserTemplate/template1.jpg'></div>";
WebBrowser wb = new WebBrowser();
wb.Navigate("about:blank");
if (wb.Document != null)
{
wb.Document.Write(html);
}
wb.DocumentText = html;
wb.ScrollBarsEnabled = false;
wb.ScriptErrorsSuppressed = true;
// Set the size of the WebBrowser control
// Take Screenshot of the web pages full width
// wb.Width = wb.Document.Body.ScrollRectangle.Width;
wb.Width = 1024;
// Take Screenshot of the web pages full height
// wb.Height = wb.Document.Body.ScrollRectangle.Height;
//wb.Height = 786;
wb.ScrollBarsEnabled = true;
if (wb.Height <= 0)
{
wb.Height = 1024;
}
//if (wb.Width <= 400)
//{
// wb.Width = 700;
//}
// Get a Bitmap representation of the webpage as it's rendered in the WebBrowser control
//Bitmap bitmap = new Bitmap(wb.Width, wb.Height);
//using (bitmap = new Bitmap(wb.Width, wb.Height))
using (bitmap = new Bitmap(wb.Width, wb.Height))
{
//wb.DrawToBitmap(bitmap, new Rectangle(0, 0, wb.Width, wb.Height));
wb.DrawToBitmap(bitmap, new Rectangle(0, 0, wb.Width, wb.Height));
//string imgPath = HttpContext.Current.Server.MapPath(System.Configuration.ConfigurationManager.AppSettings["ImgPath"].ToString());
//string imgPath="C:\\Projects\\aec\\Ace-A-Metric\\Advertiser-Admin\\Campaign\\UserTemplate\\";
string imgPath = URlPath + "test123" + ".bmp";
//bitmap.Save(#"D:\" + txtTempName.Text + ".bmp", System.Drawing.Imaging.ImageFormat.Bmp);
bitmap.Save(imgPath, System.Drawing.Imaging.ImageFormat.Bmp);
//string imgpath = Path.Combine(HttpContext.Current.Server.MapPath("~") + "Advertiser-Admin\\Campaign\\UserTemplate\\" + txtTempName.Text +".bmp");
//bitmap.Save(imgpath, System.Drawing.Imaging.ImageFormat.Bmp);
}
wb.Dispose();
GC.Collect();
}
Do not use the WebBrowser control, it is shipped with a lot of constraints due its COM legacy, and the very poor object model.
One of the possible solution is to use Awesomium.Net
Espacially, this article explain the process : Capturing Web-Pages With C# (.NET)
The major difference, is that Awesomium and its .Net wrapper is written with no dependency to the host (actually from the Chromium source code). Then the library is actually standalone and let you consider a lots of more scenarios.

File not found exception once deployed to Server

I am using the below code to Upload an Image file to a SharePoint Document Library. The code works fine locally but once deployed to server, i get the Exception as file not found.
String fileToUpload = FlUpldImage.PostedFile.FileName; //#"C:\Users\admin.RSS\Desktop\Photos\me_skype.jpg";
String documentLibraryName = "SiteAssets";
if (!System.IO.File.Exists(fileToUpload))
throw new FileNotFoundException("File not found.", fileToUpload);
SPFolder myLibrary = web.Folders[documentLibraryName];
// Prepare to upload
Boolean replaceExistingFiles = true;
String fileName = CheckStringNull(txtFirstName.Text) + CheckStringNull(txtLastName.Text) + CheckDateNull(txtDOB) + System.IO.Path.GetFileName(fileToUpload); ;
if (fileName.Contains('/'))
{
fileName = fileName.Replace("/", "");
}
if (fileName.Contains(':'))
{
fileName = fileName.Replace(":", "");
}
FileStream fileStream = File.OpenRead(fileToUpload);
//Upload document
SPFile spfile = myLibrary.Files.Add(fileName, fileStream, replaceExistingFiles);
string url = site.ToString() + "/" + spfile.ToString();
if (url.Contains("="))
{
url = url.Split('=')[1];
}
//Commit
myLibrary.Update();
The string fileupload contains URL as C:\Users\admin.RSS\Desktop\Photos\me.jpg This URL is actually the client system and the server side code throws exception as file not found. How to handle this issue?
UPDATE:
I removed the lines of code that checks if the file exists and now i get the exeption on FileStream fileStream = File.OpenRead(fileToUpload); as c:\windows\system32\inetsrv\20120605_133145.jpg cold not be found
Kindly help. Thank You
if (this.fuAvatarUpload.HasFile && this.fuAvatarUpload.PostedFile.FileName.Length > 0)
{
string extension = Path.GetExtension(file.FileName).ToLower();
string mimetype;
switch (extension)
{
case ".png":
case ".jpg":
case ".gif":
mimetype = file.ContentType;
break;
default:
_model.ShowMessage("We only accept .png, .jpg, and .gif!");
return;
}
if (file.ContentLength / 1000 < 1000)
{
Image image = Image.FromStream(file.InputStream);
Bitmap resized = new Bitmap(image, 150, 150);
byte[] byteArr = new byte[file.InputStream.Length];
using (MemoryStream stream = new MemoryStream())
{
resized.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
byteArr = stream.ToArray();
}
file.InputStream.Read(byteArr, 0, byteArr.Length);
profile.ImageUrl = byteArr;
profile.UseGravatar = false;
profileService.UpdateProfile(profile);
this._model.ShowApprovePanel();
}
else
{
_model.ShowMessage("The file you uploaded is larger than the 1mb limit. Please reduce the size of your file and try again.");
}
}
Saving the file physically onto server and than working on the same helped me resolve my issue.

Dynamically change colour of KML polygon in Google Maps API v3

I'm using Google Maps v3 API to load a KML layer and want to be able to change the colour of the KML from its default blue without having to edit the KML file itself. Is this possible using JavaScript or some other means?
Unfortunately can't post a link, but it's pretty standard stuff.
var map = new google.maps.Map(document.getElementById("mymap"), { some options });
var regionLayer = new google.maps.KmlLayer("http://.../some.kml");
regionLayer.setMap(map);
From my understanding of the documentation, 'no', but it's not especially clear. I'm trying to do a similar thing (but update the colour of mouseover/mouseout).
The KML file is loaded by the Google servers, parsed and sent along to your javascript object to be applied to the map, so, by the time your javascript KMLLayer sees it, it's all sorted out.
You may be able to do something with Styles and styleUrl. This is supposed to allow you to set a number of different styles that can then be applied at runtime, however, I haven't got it working.
I have done this by creating a web service which reads in a KML file to a string, inserts a style section to the beginning of the KML string, and also a styleURL to each uniquely named placemark. It's fairly simple to amend the markup using a .net web service and write it back out to the server you have hosting the web service.
For example this uses a class which contains placemark IDs and a colour flag:
public string KMLStyler(string URL, string URLName, Data[] MyData)
{
try
{
ReadFile(URL);
string NewKML = ReadFile(URL);
string RedStyle = "<Style id=\"red\"><LineStyle><color>7F7F7F7F</color><width>2</width></LineStyle><PolyStyle><color>7F0000FF</color><fill>1</fill><outline>1</outline></PolyStyle></Style>";
string BlackStyle = "<Style id=\"black\"><LineStyle><color>7F7F7F7F</color><width>2</width></LineStyle><PolyStyle><color>7F7F7F7F</color><fill>1</fill><outline>1</outline></PolyStyle></Style>";
string GreenStyle = "<Style id=\"green\"><LineStyle><color>7F7F7F7F</color><width>2</width></LineStyle><PolyStyle><color>7F00FF00</color><fill>1</fill><outline>1</outline></PolyStyle></Style>";
string BlueStyle = "<Style id=\"blue\"><LineStyle><color>7F7F7F7F</color><width>2</width></LineStyle><PolyStyle><color>7F7F7F7F</color><fill>1</fill><outline>1</outline></PolyStyle></Style>";
//add styles to top
int EndID = 0;
EndID = NewKML.IndexOf("</name>") + 7;
NewKML = NewKML.Insert(EndID, RedStyle);
EndID = NewKML.IndexOf("</name>") + 7;
NewKML = NewKML.Insert(EndID, BlackStyle);
EndID = NewKML.IndexOf("</name>") + 7;
NewKML = NewKML.Insert(EndID, GreenStyle);
EndID = NewKML.IndexOf("</name>") + 7;
NewKML = NewKML.Insert(EndID, BlueStyle);
//add each style to each placemark
foreach (Data MyDataSingle in MyData)
{
int NamePos = NewKML.IndexOf(MyDataSingle.Name);
if (NamePos == -1) throw new Exception("Did not find '" + MyDataSingle.Name + "' within File");
NamePos += MyDataSingle.Name.Length + 7;
int MultiGeometryStartPos = NewKML.IndexOf("<MultiGeometry>", NamePos);
int MultiGeometryEndPos = NewKML.IndexOf("</MultiGeometry>", NamePos);
int PolygonStartPos = NewKML.IndexOf("<Polygon>", NamePos);
int InsertPos = 0;
if (MultiGeometryStartPos < PolygonStartPos)
{
if (MultiGeometryStartPos != -1)
{
InsertPos = MultiGeometryStartPos;
}
else
{
InsertPos = PolygonStartPos;
}
}
else
{
InsertPos = PolygonStartPos;
}
if (MyDataSingle.Red)
{
NewKML = NewKML.Insert(InsertPos, "<styleUrl>#red</styleUrl>");
}
if (MyDataSingle.Black)
{
NewKML = NewKML.Insert(InsertPos, "<styleUrl>#black</styleUrl>");
}
if (MyDataSingle.Green)
{
NewKML = NewKML.Insert(InsertPos, "<styleUrl>#green</styleUrl>");
}
if (MyDataSingle.Blue)
{
NewKML = NewKML.Insert(InsertPos, "<styleUrl>#blue</styleUrl>");
}
}
string NewFileName = WriteFile(NewKML, URLName);
return NewFileName;
}
catch (Exception ex)
{
return ex.ToString();
}
}
public string WriteFile(string KMLData, string URLName)
{
string FileName = "http:\\blah.co.uk\blah.kml";
StreamWriter writer = new StreamWriter("C:/inetpub/blah.kml");
writer.Write(KMLData);
writer.Flush();
writer.Close();
return FileName;
}
public string ReadFile(string URL)
{
string File = "";
StreamReader reader = new StreamReader(WebRequest.Create(URL).GetResponse().GetResponseStream());
string line;
while ((line = reader.ReadLine()) != null)
{
File += line;
}
return File;
}

Resize image while uploading

i am using file upload control for uploading images.
in that iam checking the condition,if Image.Width > 250 || Image.Height > 400 then i am resizing the image.
but it is giving the error
"The SaveAs method is configured to require a rooted path, and the path 'ProductImages/roman_sandals.jpg' is not rooted."
ProductImages is folder where i am saving image.
Can anyone find why this is giving error,my code is
string strBigServerPath = AppHardcodeValue.productImgPath;
string strFileName = "";
if (prodImg.HasFile)
{
strFileName = prodImg.PostedFile.FileName;
string uniqueNum = Convert.ToString(System.Guid.NewGuid());
string shortFileName = System.IO.Path.GetFileName(strFileName);
string Extension = System.IO.Path.GetExtension(prodImg.FileName);
string newFileName = shortFileName;
prodImg.SaveAs(Server.MapPath(strBigServerPath + newFileName));
using (System.Drawing.Image Img =
System.Drawing.Image.FromFile(Server.MapPath(strBigServerPath) + newFileName))
{
if (Img.Width > 250 || Img.Height > 400)
{
Size MainSize = new Size(250, 400);
using (System.Drawing.Image ImgThnail =
new Bitmap(Img, MainSize.Width, MainSize.Height))
{
prodImg.SaveAs(strBigServerPath + newFileName);
}
}
Img.Dispose();
}
string ThumbnailPath = Server.MapPath(AppHardcodeValue.productThumbImgPath) + newFileName;
using (System.Drawing.Image Img =
System.Drawing.Image.FromFile(Server.MapPath(strBigServerPath) + newFileName))
{
Size ThumbNailSize = new Size(50, 50);
using (System.Drawing.Image ImgThnail =
new Bitmap(Img, ThumbNailSize.Width, ThumbNailSize.Height))
{
ImgThnail.Save(ThumbnailPath, Img.RawFormat);
ImgThnail.Dispose();
}
Img.Dispose();
}
}
You can use
HostingEnvironment.ApplicationPhysicalPath
in this case, and combine it with your image path.
For example:
Path.Combine(HostingEnvironment.ApplicationPhysicalPath, "ProductImages/roman_sandals.jpg");
which will give you a rooted path. The folder "ProductImages" has to be located in the applications directory.
See here for details: http://msdn.microsoft.com/en-us/library/system.web.hosting.hostingenvironment.applicationphysicalpath.aspx

Resources