我创建了一个图片上传器,供用户上传/裁剪他们的个人资料照片。当用户上传文件时,该文件会保存到一个文件中,以便他们对其进行裁剪后立即访问。
我尝试使用Path.GetTempPath()以及Path.GetTempFileName(),但是由于某些原因,我的裁剪器无法找到文件位置。 任何建议都将不胜感激。
更新:因此我在btnCropClick的末尾添加了File.Delete(filePath),但出现一条错误消息,指出该进程无法访问该文件,因为该文件正在被另一个进程使用。我如何“释放”要立即删除的文件?
下面是用户上传其选择的原始图片的代码
protected void btnUploadClick(object sender,EventArgs e)
{
//Upload Original Image Here
String UploadFileName = "";
String UploadFilePath = "";
if (fileUploader.HasFile)
{
String ext = Path.GetExtension(fileUploader.FileName).ToLower();
if (ext == ".jpg" || ext == ".jpeg" || ext == ".png")
{
UploadFileName = "orig_" + Guid.NewGuid().ToString() + ext;
UploadFilePath = Path.Combine(Server.MapPath("images/OriginalImages"),UploadFileName);
try
{
fileUploader.SaveAs(UploadFilePath); //TODO: Need to make this a temp file that gets "destroyed" later
imgUpload.ImageUrl = "images/OriginalImages/" + UploadFileName;
panCrop.Visible = true;
}
catch (Exception ex)
{
lblMsg.Text = "Error! Please Try Again. ";
}
}
else
{
lblMsg.Text = "Invalid File Type Selected. | Please Choose .jpg,.jpeg,or .png file only.";
}
}
else
{
lblMsg.Text = "Please Click 'Choose File' & Select An Image To Upload";
}
}
这是裁剪机的代码(不确定此处是否需要更改,但是为了上下文和相关性,我还是将其包括在内
protected void btnCropClick(object sender,EventArgs e)
{
//Crop Image Here & Save
String fileName = Path.GetFileName(imgUpload.ImageUrl);
String filePath = Path.Combine(Server.MapPath("images/OriginalImages"),fileName);
String cropFileName = "";
String cropFilePath = "";
if (File.Exists(filePath))
{
System.Drawing.Image orgImg = System.Drawing.Image.FromFile(filePath);
Rectangle CropArea = new Rectangle(
Convert.ToInt32(X.Value),Convert.ToInt32(Y.Value),Convert.ToInt32(W.Value),Convert.ToInt32(H.Value)
);
try
{
Bitmap bitMap = new Bitmap(CropArea.Width,CropArea.Height);
using (Graphics g = Graphics.FromImage(bitMap))
{
g.DrawImage(orgImg,new Rectangle(0,bitMap.Width,bitMap.Height),CropArea,GraphicsUnit.Pixel);
Bitmap resized = new Bitmap(bitMap,new Size(200,200)); //Resize image to save as 200x200
cropFileName = "crop_" + fileName; //+UserID so each fileName is unique
cropFilePath = Path.Combine(Server.MapPath("images/CroppedImages"),cropFileName);
resized.Save(cropFilePath); //Where final,cropped image is saved
imgHeadshot.ImageUrl = "images/CroppedImages/" + cropFileName;
}
}
catch (Exception ex)
{
throw;
}
panCrop.Visible = false;
}
}