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);
Related
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
}
i have this c# asp dot net code to add water mark on the asp image control which is working fine.
string watermarkText = "© water mark";
string fileName = Server.MapPath(myimg.ImageUrl);
FileStream fs = new FileStream(fileName, FileMode.Open);
using (Bitmap bmp = new Bitmap(fs, false))
{
using (Graphics grp = Graphics.FromImage(bmp))
{
Brush brush = new SolidBrush(Color.Red);
Font font = new System.Drawing.Font("Arial", 30, FontStyle.Bold, GraphicsUnit.Pixel);
SizeF textSize = new SizeF();
textSize = grp.MeasureString(watermarkText, font);
Point position = new Point((bmp.Width - ((int)textSize.Width + 10)), (bmp.Height - ((int)textSize.Height + 80)));
grp.DrawString(watermarkText, font, brush, position);
using (MemoryStream memoryStream = new MemoryStream())
{
bmp.Save(memoryStream, ImageFormat.Png);
string base64String = Convert.ToBase64String(memoryStream.ToArray());
string imageUrl = "data:image/png;base64," + base64String;
myimg.Attributes.Add("src", imageUrl);
}
}
}
but when i add the same water mark code inside listview on listview databound event like
System.Web.UI.WebControls.Image myimg;
protected void ListView1_ItemDataBound(object sender, ListViewItemEventArgs e)
{
if (!IsPostBack)
{
if (e.Item.ItemType == ListViewItemType.DataItem)
{
myimg = ((System.Web.UI.WebControls.Image)e.Item.FindControl("Image1"));
string watermarkText = "© watermark";
string fileName = Server.MapPath(myimg.ImageUrl);
FileStream fs = new FileStream(fileName, FileMode.Open);
using (Bitmap bmp = new Bitmap(fs, false))
{
using (Graphics grp = Graphics.FromImage(bmp))
{
Brush brush = new SolidBrush(Color.Red);
Font font = new System.Drawing.Font("Arial", 30, FontStyle.Bold, GraphicsUnit.Pixel);
SizeF textSize = new SizeF();
textSize = grp.MeasureString(watermarkText, font);
Point position = new Point((bmp.Width - ((int)textSize.Width + 10)), (bmp.Height - ((int)textSize.Height + 80)));
grp.DrawString(watermarkText, font, brush, position);
using (MemoryStream memoryStream = new MemoryStream())
{
bmp.Save(memoryStream, ImageFormat.Png);
string base64String = Convert.ToBase64String(memoryStream.ToArray());
string imageUrl = "data:image/png;base64," + base64String;
myimg.Attributes.Add("src", imageUrl);
}
}
}
}
}
}
so it gives me following error CustomCoupon\ca00453f-c985-4794-9a87-36a60e2fa0e1.png' because it is being used by another process.
Please advice.
You can replace:
FileStream fs = new FileStream(fileName, FileMode.Open);
by:
using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
{
...
}
private bool ReturnVideo(string fileName)
{
string html = string.Empty;
//rename if file already exists
int j = 0;
string AppPath;
string inputPath;
string outputPath;
// string imgpath;
AppPath = Request.PhysicalApplicationPath;
//Get the application path
inputPath = AppPath + "OriginalVideo";
//Path of the original file
outputPath = AppPath + "ConvertVideo";
//Path of the converted file
// imgpath = AppPath + "Thumbs";
//Path of the preview file
string filepath = Server.MapPath("~/OriginalVideo/" + fileName);
while (File.Exists(filepath))
{
j = j + 1;
int dotPos = fileName.LastIndexOf(".");
string namewithoutext = fileName.Substring(0, dotPos);
string ext = fileName.Substring(dotPos + 1);
fileName = namewithoutext + j + "." + ext;
filepath = Server.MapPath("~/OriginalVideo/" + fileName);
}
try
{
this.fileuploadImageVideo.SaveAs(filepath);
}
catch
{
// return false;
}
string outPutFile;
outPutFile = "~/OriginalVideo/" + fileName;
int i = this.fileuploadImageVideo.PostedFile.ContentLength;
System.IO.FileInfo a = new System.IO.FileInfo(Server.MapPath(outPutFile));
string cmd = "-y -ss 00:00:00 -to 00:00:10 -i " + inputPath + "\\" + fileName + " -vcodec copy -acodec copy " + outputPath + "\\" + fileName.Remove(fileName.IndexOf(".")) + ".mp4";
ConvertNow(cmd);
return true;
}
private void ConvertNow(string cmd)
{
string exepath;
string AppPath = Request.PhysicalApplicationPath;
//Get the application path
exepath = AppPath + "ffmpeg\\ffmpeg.exe";
Process proc = new Process();
proc.StartInfo.FileName = exepath;
//Path of exe that will be executed, only for "filebuffer" it will be "flvtool2.exe"
proc.StartInfo.Arguments = cmd;
//The command which will be executed
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.CreateNoWindow = true;
proc.StartInfo.RedirectStandardOutput = false;
proc.Start();
//while (proc.HasExited == false)
//{
//}
}
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")
I create a PDF file using iTextSharp and it's stored in my system desktop and opens successfully in my local system. Now if I upload the same code to a server, no error occurs and the PDF file isn't created. This is my partial code to create and open pdf.
PdfWriter.GetInstance(doc, new FileStream(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\Out.pdf", FileMode.Create));
doc.Open();
DataView DView = (DataView)Session["data_value"];
dtData = DView.ToTable();
dr = dtData.Select("fldemp_no='" + Session["EmployeeID"].ToString() + "'");
doc.NewPage();
iTextSharp.text.Image ObjImg = iTextSharp.text.Image.GetInstance(Server.MapPath("~/Bin/Head.png"));
ObjImg.Alignment = iTextSharp.text.Image.ALIGN_CENTER;
ObjImg.ScaleToFit(220f, 150f);
ObjImg.SpacingBefore = 13f;
ObjImg.SpacingAfter = 1f;
doc.Add(ObjImg);
maintable = new PdfPTable(1);
cell = new PdfPCell(new Phrase("Pay Slip for the month of " + dr[0]["fldmonth"].ToString(), fnt1));
cell.HorizontalAlignment = Element.ALIGN_CENTER;
cell.Border = 0;
maintable.AddCell(cell);
doc.Add(maintable);
maintable = new PdfPTable(2);
empdetright = new PdfPTable(2);
empdetleft = new PdfPTable(2);
cell = new PdfPCell(new Phrase("Emp No", fnt1));
cell.Border = 0;
empdetright.AddCell(cell);
cell = new PdfPCell(new Phrase(": " + dr[0]["fldemp_no"].ToString(), fnt1));
cell.Border = 0;
empdetright.AddCell(cell);
cell = new PdfPCell(new Phrase("Emp Name", fnt1));
cell.Border = 0;
empdetright.AddCell(cell);
cell = new PdfPCell(new Phrase(": " + dr[0]["fldempname"].ToString(), fnt1));
cell.Border = 0;
empdetright.AddCell(cell);
doc.Close();
Process.Start(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "/out.pdf");
In a web application you need to return the PDF document in the response stream. Here is a simple example:
var response = HttpContext.Current.Response;
response.Clear();
response.ContentType = "application/pdf";
MemoryStream mem = new MemoryStream(); // PDF data will be written here
PdfWriter writer = PdfWriter.GetInstance(doc, mem); // tie a PdfWriter instance to the stream
doc.Open();
// ... Doing the pdf generation
doc.Close();
// write the document data to response stream
writer.Flush();
response.OutputStream.Write(mem.GetBuffer(), 0, mem.GetBuffer().Length);
response.OutputStream.Flush();
response.OutputStream.Close();
response.End();