upload image as 24bit pixel format - asp.net

I use an asp file uploader to upload a bitmap image. The original image is saved in hard disk in 24 bit format but the uploader converted it to 32 bit and subsequently gives wrong result in my web application
How can I upload image as its original 24 bit?
Dim face As search_eng.face
face = New face() ' initialize object (face)
If (Not System.IO.Directory.Exists(getpath() + "\pics\")) Then
System.IO.Directory.CreateDirectory(getpath() + "\pics\")
End If
Dim i = 0
While System.IO.File.Exists(getpath() + "\pics\" + i.ToString + ".jpg")
i += 1
End While
FileUpload1.SaveAs(getpath() + "\pics\" + i.ToString + ".jpg")
Image1.ImageUrl = "\pics\" + i.ToString + ".jpg"
Dim fs As System.IO.FileStream ' define a file stream
fs = New IO.FileStream(getpath() + "\pics\" + i.ToString + ".jpg", IO.FileMode.Open, IO.FileAccess.Read) ' open for read
Dim img As System.Drawing.Image
img = System.Drawing.Image.FromStream(fs)
fs.Dispose()
Dim btimg As System.Drawing.Bitmap
Dim Original_img As System.Drawing.Bitmap
btimg = New Drawing.Bitmap(img, img.Width, img.Height)
Original_img = New Drawing.Bitmap(img, img.Width, img.Height)
img = btimg
Original_img = btimg
Original_img.Save("d:\after_open_Web.bmp")

Related

Resize image on server without download

I have images present on server in asp.net. I want to create their thumbnails by just copying, resizing, renaming and at last saving them on server itself. For compression I have the code but how can I Save the file.
if (fileUploader.HasFile)
{
string fileName = Path.GetFileName(fileUploader.PostedFile.FileName);
string ext = string.Empty;
ext = System.IO.Path.GetExtension(fileUploader.FileName.ToString()).ToLower();
fileUploader.PostedFile.SaveAs(Server.MapPath("~/Images_Coach/" + hdnCoachId.Value + "/") + hdnCoachId.Value + ext);
int width = Convert.ToInt32(150);
int height = Convert.ToInt32(150);
Stream inp_Stream = fileUploader.PostedFile.InputStream;
using (var image = System.Drawing.Image.FromStream(inp_Stream))
{
Bitmap myImg = new Bitmap(width, height);
Graphics myImgGraph = Graphics.FromImage(myImg);
myImgGraph.CompositingQuality = CompositingQuality.HighQuality;
myImgGraph.SmoothingMode = SmoothingMode.HighQuality;
myImgGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;
var imgRectangle = new Rectangle(0, 0, width, height);
myImgGraph.DrawImage(image, imgRectangle);
newFile = hdnCoachId.Value + "_icon" + ext;
// Save the file
var path = Path.Combine(Server.MapPath("~/Images_Coach/" + hdnCoachId.Value + "/"), newFile);
myImg.Save(path, image.RawFormat);
}
}
I can get the file into byte array and then convert it into stream
foreach (var fileName in Directory.GetFiles(dirFile))
{
if (fileName.Contains(dir))
{
string newFile = string.Empty;
//Read the File into a Byte Array.
string ext = string.Empty;
ext = System.IO.Path.GetExtension(fileName.ToString()).ToLower();
byte[] bytes = File.ReadAllBytes(fileName);
Stream inp_Stream = new MemoryStream(bytes);
int width = Convert.ToInt32(150);
int height = Convert.ToInt32(150);
using (var image = System.Drawing.Image.FromStream(inp_Stream))
{
Bitmap myImg = new Bitmap(width, height);
Graphics myImgGraph = Graphics.FromImage(myImg);
myImgGraph.CompositingQuality = CompositingQuality.HighQuality;
myImgGraph.SmoothingMode = SmoothingMode.HighQuality;
myImgGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;
var imgRectangle = new Rectangle(0, 0, width, height);
myImgGraph.DrawImage(image, imgRectangle);
newFile = dir + "_icon" + ext;
// Save the file
var newPath = Path.Combine(Server.MapPath("~/Images_Coach/" + dir + "/"), newFile);
myImg.Save(newPath, image.RawFormat);
}
}
//File.Delete
// fileName is the file name
}

TreeView expanding wrong node

I have a TreeView in a VB.NET/ASP.NET Application.
The TreeView is being Populated programmatically as the page loads. However, when i try and expand a node it is expanding the wrong node.
Example:I have a node with 5 children. Nodes one and two have children and when i try and expand node two it expands node one and when i try and expand node one it also expands node one.
I have tried re-organizing the structure of the TreeView and Also tried adding the nodes in one by one and still no luck.
Edit:
Below is the Relevant code from my TreeView :
For Each V2MaterialRow In DS.Tables("AllinOne").Rows
connection.Open()
command = New SqlCommand("Select FormName from ISO where PageTitle='Material Details'", connection)
Dim FormName As String = command.ExecuteScalar()
connection.Close()
V2MaterialNode = New TreeNode
V2MaterialNode.ToolTip = "V2 Material Details"
V2MaterialNode.Text = FormName & " " & V2MaterialRow("Version")
V2MaterialNode.Value = V2MaterialRow("Qno")
V2MaterialNode.ShowCheckBox = True
V2MaterialNode.NavigateUrl = "V2MaterialDetails.aspx?text=" + V2MaterialRow("Qno")
V2MaterialNode.Target = "_blank"
node.ChildNodes.Add(V2MaterialNode)
connection.Open()
command = New SqlCommand("Select * from Specallinone where qno='" + V2MaterialRow("Qno") + "'", connection)
datareader = command.ExecuteReader()
If datareader.HasRows = False Then
datareader.Close()
For Each PurchaseOrderRow In DS.Tables("PurchaseOrder").Rows
PurchaseOrderNode = New TreeNode
PurchaseOrderNode.ToolTip = "Purchase Order"
PurchaseOrderNode.Text = "Purchase Order - " + PurchaseOrderRow("supplier") + " " + PurchaseOrderRow("Ordernumber")
PurchaseOrderNode.Value = PurchaseOrderRow("Qno")
PurchaseOrderNode.NavigateUrl = "PurchaseOrder.aspx?qno=" + PurchaseOrderRow("Qno") + "&Jobno=" + PurchaseOrderRow("JobNumber") + "&Orderno=" + PurchaseOrderRow("Ordernumber") + "&text=" + Replace(PurchaseOrderRow("supplier"), "&", "$") + ""
PurchaseOrderNode.Target = "_blank"
V2MaterialNode.ChildNodes.Add(PurchaseOrderNode)
Next
Else
datareader.Close()
End If
connection.Close()
For Each LabelRow As DataRow In DS.Tables("AllinOne").Rows
Dim Labelnode = New TreeNode
Labelnode.ToolTip = "PO Labels"
Labelnode.Text = "PO Labels"
Labelnode.Value = LabelRow("Qno")
'Labelnode.ShowCheckBox = True
Labelnode.NavigateUrl = "GeneratePOLabels.aspx?text=" + LabelRow("Qno")
Labelnode.Target = "_blank"
Try
connection.Open()
command = New SqlCommand("Select * from purchaseorder where qno='" + LabelRow("Qno") + "' and Jobnumber<>''", connection)
datareader = command.ExecuteReader()
If datareader.HasRows = False Then
datareader.Close()
Exit For
Else
datareader.Close()
V2MaterialNode.ChildNodes.Add(Labelnode)
End If
Catch ex As Exception
Messagebox.Show("Error in Dispalying the Labels...")
Finally
connection.Close()
End Try
Next
Next
For Each MPORow In DS.Tables("ManualPO").Rows
Dim Supplier As String
connection.Open()
command = New SqlCommand("Select Distinct Supplier from ManualPurchaseOrder where ManualDetailsId='" + MPORow("ManualDetailsId").ToString + "' ", connection)
datareader = command.ExecuteReader()
While datareader.Read()
Supplier = Supplier + datareader.Item("Supplier") + ","
End While
datareader.Close()
connection.Close()
MPONode = New TreeNode
MPONode.Value = MPORow("ManualDetailsId")
MPONode.Text = "Manual PO " & MPORow("ManualDetailsId") & " Supplier:" & Supplier.ToString
Supplier = ""
node.ChildNodes.Add(MPONode)
Dim ManualPODetailsDa As New SqlDataAdapter("Select distinct supplier,Jobnumber,ordernumber,Qno from PurchaseOrder where Ordernumber in (Select Distinct OrderNumber From ManualPurchaseOrder where ManualDetailsId = '" + MPORow("ManualDetailsId") + "') ", connection)
Dim ManualPODetailsDs As New DataSet
ManualPODetailsDa.Fill(ManualPODetailsDs)
For Each ManualPODetailsDR As DataRow In ManualPODetailsDs.Tables(0).Rows
MPODNode = New TreeNode
MPODNode.Value = ManualPODetailsDR("OrderNumber")
MPODNode.Text = "Purchase Order - " + ManualPODetailsDR("supplier") + " " + ManualPODetailsDR("Ordernumber")
MPODNode.NavigateUrl = "PurchaseOrder.aspx?qno=" + ManualPODetailsDR("Qno") + "&Jobno=" + ManualPODetailsDR("JobNumber") + "&Orderno=" + ManualPODetailsDR("Ordernumber") + "&text=" + Replace(ManualPODetailsDR("supplier"), "&", "$") + ""
MPODNode.Target = "_blank"
MPONode.ChildNodes.Add(MPODNode)
Next
Next
For Each Takeoffrow In DS.Tables("AllinOne").Rows
connection.Open()
command = New SqlCommand("Select FormName from ISO where PageTitle='Take-Off-Sheets'", connection)
Dim FormName As String = command.ExecuteScalar()
TakeOffNode = New TreeNode
TakeOffNode.ToolTip = "Take Off Sheets"
TakeOffNode.Text = FormName & " " & Takeoffrow("Version")
TakeOffNode.Value = Takeoffrow("Qno")
TakeOffNode.ShowCheckBox = True
TakeOffNode.NavigateUrl = "TakeOffSheet.aspx?text=" + Takeoffrow("Qno")
TakeOffNode.Target = "_blank"
node.ChildNodes.Add(TakeOffNode)
command = New SqlCommand("Select count(*) from ManualTakeOffSheet where srecid in (Select Distinct Srecid from Specdetails where Quoteno='" + Takeoffrow("Qno") + "')", connection)
Dim MTS As Integer = 0
MTS = command.ExecuteScalar()
connection.Close()
If MTS > 0 Then
Dim ManualTakeoffnode As New TreeNode
ManualTakeoffnode.ToolTip = "Manual Take Off Sheets"
ManualTakeoffnode.Text = "Manual Take Off Sheets" & " " & Takeoffrow("Version")
ManualTakeoffnode.Value = Takeoffrow("Qno")
ManualTakeoffnode.NavigateUrl = "ManualTakeOffSheet.aspx?text=" + Takeoffrow("Qno")
ManualTakeoffnode.Target = "_blank"
TakeOffNode.ChildNodes.Add(ManualTakeoffnode)
End If
Next
Sometimes if you have a node which shares the same value as another node - unexpected behavior can occur (one node opening when the other is clicked)
Node values must be unique
Debug your code and ensure that all your nodes have a unique value.
The value will be stored in node.Value
In your case, the node.Value is populated from a table.
Ensure that TakeOffNode.Value = Takeoffrow("Qno") does not equal MPODNode.Value = ManualPODetailsDR("OrderNumber")

Saving Multiple Image Path url in Database at once

My multiple image upload code works fine. But while inserting the image path url in the database only one image path is saved. How can i save all the image path url's at once.
Here is my GetPictureData()
public string GetPictureData()
{
string retFileName = "";
try
{
if (((FileUpload1.PostedFile != null)))
{
if ((FileUpload1.PostedFile.ContentType.ToUpper().Contains("IMAGE")))
{
HttpFileCollection hfc = Request.Files;
for (int i = 0; i < hfc.Count; i++)
{
HttpPostedFile hpf = hfc[i];
if (hpf.ContentLength > 0)
{
//Stream inStream = hpf.InputStream;
//byte[] fileData = new byte[hpf.ContentLength];
//inStream.Read(fileData, 0, hpf.ContentLength);
String sTimeStamp = GetTimeStamp();
string iFileName = System.IO.Path.GetFileName(hpf.FileName);
string newFileName = iFileName.Replace(" ", "_");
string OutFile = Server.MapPath(ConfigurationManager.AppSettings["LocalImageDirectory"]) + "\\" + sTimeStamp + "_" + newFileName;
hpf.SaveAs(OutFile);
OutFile = ConfigurationManager.AppSettings["LocalImageDirectory"] + "\\" + sTimeStamp + "_" + newFileName;
retFileName = OutFile;
}
}
}
}
}
catch(Exception ex)
{
string msg = ex.Message;
Response.Write(msg);
}
return retFileName;
}
and here is my UploadButton code
protected void btnUpload_Click(object sender, EventArgs e)
{
if (Session["localauctionid"] != null && Session["localauctionid"].ToString() != "")
{
string filepath = GetPictureData();
if (filepath != "")
{
string sqlcommand = " insert into auctionimages (auctionid, ImagePath, GalleryPic) values(" + Session["localauctionid"].ToString() + ",'" + filepath + "', 0);" +
" update auctionstep1 set ListingStatus = 'Photographed' where auctionid = " + Session["localauctionid"].ToString() + " and (listingstatus <> 'Created' AND listingstatus <> 'Saved');";
Database db = DatabaseFactory.CreateDatabase();
DbCommand cmd = db.GetSqlStringCommand(sqlcommand);
db.ExecuteNonQuery(cmd);
LoadImages();
}
}
}
Thanks
You error lies in the fact that the GetPictureData loops over a collection of files, but only the last file is returned to the button event where you call the save to database code. Of course, only the last file will be saved in the database.
The workaround is to create a standalone method to save in the database where you pass the filename and the localAuctionID. You call this method inside the GetPictureData (renamed more correctly to SavePictureData) internal loop for each file to be saved
As a pseudocode (not tested)
private void SaveToDb(int localAutID, string filepath)
{
string sqlcommand = " insert into auctionimages (auctionid, ImagePath, GalleryPic) " +
"values(#auID, #file, 0); " +
" update auctionstep1 set ListingStatus = 'Photographed' " +
"where auctionid = #auID and (listingstatus <> 'Created' " +
"AND listingstatus <> 'Saved');";
Database db = DatabaseFactory.CreateDatabase();
DbCommand cmd = db.GetSqlStringCommand(sqlcommand);
DbParameter p1 = cmd.CreateParameter()
{ParameterName="#auID", DbType=DbType.Int32, Value=localAutID};
DbParameter p2 = cmd.CreateParameter()
{ParameterName="#file", DbType=DbType.AnsiString, Value=filepath};
db.ExecuteNonQuery(cmd);
}
And if SavePictureData call it inside the for loop
for (int i = 0; i < hfc.Count; i++)
{
.....
retFileName = OutFile;
SaveToDb(Convert.ToInt32(Session["localauctionid"]), retFileName);
}
if (Session["localauctionid"] != null && Session["localauctionid"].ToString() != "")
{
string filepath = GetPictureData();
if (filepath != "")
{
string sqlcommand = " insert into auctionimages (auctionid, ImagePath, GalleryPic) values(" + Session["localauctionid"].ToString() + ",'" + filepath + "', 0);" +
" update auctionstep1 set ListingStatus = 'Photographed' where auctionid = " + Session["localauctionid"].ToString() + " and (listingstatus <> 'Created' AND listingstatus <> 'Saved');";
Database db = DatabaseFactory.CreateDatabase();
DbCommand cmd = db.GetSqlStringCommand(sqlcommand);
db.ExecuteNonQuery(cmd);
LoadImages();
}
The person only clicks the upload button once - hence only one image being saved.
Personally I would evaluate the way you have coded this. I would move the code you use to save the image to the db into a stand alone method and call it when the image upload is complete in GetPictureData()

Image from file, Server MapPath

Why does this work:
System.Drawing.Image imageBmp =
System.Drawing.Image.FromFile(Server.MapPath("~/Images/Image.jpg"));
imageBmp.Save(Server.MapPath("~/Images2/Image.jpg"),
System.Drawing.Imaging.ImageFormat.Bmp);
Bitmap bmp = new Bitmap(imageBmp);
And this not? (the filename is correct)
var fileName = Request.QueryString["name"];
System.Drawing.Image imageBmp =
System.Drawing.Image.FromFile(Server.MapPath("~/Images/" + fileName));
imageBmp.Save(Server.MapPath("~/Images/" + fileName),
System.Drawing.Imaging.ImageFormat.Bmp);
Bitmap bmp = new Bitmap(imageBmp);
This line will try to save a file onto itself imageBmp.Save(Server.MapPath("~/Images/" + fileName),
System.Drawing.Imaging.ImageFormat.Bmp);
It should be imageBmp.Save(Server.MapPath("~/Images2/" + fileName),
System.Drawing.Imaging.ImageFormat.Bmp);

System.Runtime.InteropServices.ExternalException: A generic error occurred in GDI+. imp

hye....its kinda urgent...
iam using a temp folder to store images for the preview and when i try to save them a System.Runtime.InteropServices.ExternalException: A generic error occurred in GDI+ erreo is reported...
If FileUpload1.HasFile Then
Dim path As String = Server.MapPath("./TempImages/")
Dim oFileInfo As New FileInfo(FileUpload1.PostedFile.FileName)
Dim fileName As String = oFileInfo.Name
Dim fullFileName As String = path + "\\" + fileName
Dim imagePath As String = "TempImages/" + fileName
If Not Directory.Exists(path) Then
Directory.CreateDirectory(path)
End If
FileUpload1.PostedFile.SaveAs(fullFileName)
Image1.ImageUrl = imagePath
this is what iam doing and to save
If (FileUpload1.HasFile) Then
Dim strextension As String = System.IO.Path.GetExtension(FileUpload1.FileName)
If (strextension.ToUpper() = ".JPG") Then
Dim imagetoberezised As System.Drawing.Image = System.Drawing.Image.FromStream(FileUpload1.PostedFile.InputStream)
Dim imageheight As Integer = imagetoberezised.Height
Dim imagewidth As Integer = imagetoberezised.Width
Dim maxheight As Integer = 120
Dim maxwidth As Integer = 80
imageheight = (imagewidth * maxheight) / imageheight
imagewidth = maxheight
If imageheight > maxheight Then
imageheight = (imagewidth * maxheight) / imageheight
imagewidth = maxheight
End If
Dim bitmap As New Bitmap(imagetoberezised, imagewidth, imageheight)
Dim stream As System.IO.MemoryStream = New MemoryStream()
bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg)
stream.Position = 0
Dim img As Byte() = New Byte(stream.Length) {}
stream.Read(img, 0, img.Length)
Dim conn5 As New SqlConnection
conn5 = New SqlConnection
conn5.ConnectionString = "Server=aa-pc;Database=abcc;Uid=sa;Pwd=sa#123;"
Try
conn5.Open()
Dim sql As String = "update abcset abc_IMAGE = #eimg where PART_NO=" & Val(Part_List.SelectedValue)
Dim cmd5 As SqlCommand = New SqlCommand(sql, conn5)
Dim uploadimage As New SqlParameter("#eimg", SqlDbType.Image, img.Length)
uploadimage.Value = img
cmd5.Parameters.Add(uploadimage)
Dim id As Integer = Convert.ToInt32(cmd5.ExecuteScalar())
Catch
MsgBox("error")
Finally
conn5.Close()
End Try
End If
End If
it works well whilw we run it locally but not on server..
Try this, it work for me:
Dim path As String = Server.MapPath("~/TempImages")
Dim FileInfo As New IO.FileInfo(FileUpload1.PostedFile.FileName)
Dim fileName As String = FileInfo.Name
'sets the image path
Dim fullFileName As String = path + "\" + fileName
Dim imagePath As String = "TempImages/" + fileName
'If Not Directory.Exists(path) Then
If Not System.IO.Directory.Exists("directory path") Then
System.IO.Directory.Exists("directory path")
End If
FileUpload1.PostedFile.SaveAs(fullFileName)
Image1.ImageUrl = imagePath

Resources