How to access the path? - c#

I want to store the image in a folder. For that, i give path of folder as "D:\Project\Site\ImageFiles". By using this path, I stored the image in the folder successfully.
Now I want to store the image by giving path as "..\Project\Site\ImageFiles".
Here is the code:
public static bool SaveOriginalImage(string imageName, Image image)
{
try
{
var imageLocation = "D:\Project\Site\ImageFiles\";
if (!Directory.Exists(imageLocation))
{
Directory.CreateDirectory(imageLocation);
}
imageLocation = imageLocation + imageName;
var bitMapImage = new Bitmap(image.Width, image.Height);
bitMapImage.SetResolution(image.HorizontalResolution, image.VerticalResolution);
using (var graphicImageContent = Graphics.FromImage(bitMapImage))
{
graphicImageContent.CompositingQuality = CompositingQuality.HighQuality;
graphicImageContent.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphicImageContent.SmoothingMode = SmoothingMode.HighQuality;
graphicImageContent.DrawImage(image, 0, 0, image.Width, image.Height);
}
bitMapImage.Save(imageLocation);
bitMapImage.Dispose();
return true;
}
catch (Exception ex)
{
return false;
}
}
When giving path as "..\Project\Site\ImageFiles\", i get exception "Access is denied for the path ..\Project\Site\ImageFiles\ " when creating directory.
How can I achieve it?

var fullPath = Path.GetFullPath("..\Project\Site\ImageFiles")
https://msdn.microsoft.com/de-de/library/system.io.path(v=vs.110).aspx

Related

Convert IFormFile to Image in Asp Core

i need to resize file upload if file is image .
i write the extention for resize that :
public static Image ResizeImage(this Image image, int width, int height)
{
var res = new Bitmap(width, height);
using (var graphic = Graphics.FromImage(res))
{
graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphic.SmoothingMode = SmoothingMode.HighQuality;
graphic.PixelOffsetMode = PixelOffsetMode.HighQuality;
graphic.CompositingQuality = CompositingQuality.HighQuality;
graphic.DrawImage(image, 0, 0, width, height);
}
return res;
}
and this is Upload Action :
[HttpPost("UploadNewsPic"), DisableRequestSizeLimit]
public IActionResult UploadNewsPic(IFormFile file)
{
if (file.IsImage())
{
}
try
{
if (file.Length > 0)
{
string fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
string fullPath = Path.Combine(_applicationRoot.UploadNewPath(), file.Name);
using (var stream = new FileStream(fullPath, FileMode.Create))
{
file.CopyTo(stream);
}
}
return Ok();
}
catch (Exception e)
{
return BadRequest();
}
}
now my problem is here => my extention just work on type of Image file but type of this file is IFormFile . how can i convert the IFormFile to Image type ?
You should use the Image.FromStream() method to read the stream as an Image:
public async Task<IActionResult> FileUpload(IFormFile file)
{
if (file == null || file.Length == 0)
{
return BadRequest();
}
using (var memoryStream = new MemoryStream())
{
await file.CopyToAsync(memoryStream);
using (var img = Image.FromStream(memoryStream))
{
// TODO: ResizeImage(img, 100, 100);
}
}
}
You need to open file using OpenReadStream and convert into image format. And pass the same to your extension method.
FileDetails fileDetails;
using (var reader = new StreamReader(file.OpenReadStream()))
{
var fileContent = reader.ReadToEnd();
var parsedContentDisposition = ContentDispositionHeaderValue.Parse(file.ContentDisposition);
fileDetails = new FileDetails
{
Filename = parsedContentDisposition.FileName,
Content = fileContent,
ContentType=file.ContentType
};
}

Resized image locked file

This is my code to resize an image. It works fine but when I try to delete the previously created, I have an error "file is used by another process". This is the code:
try
{
int newHeight = width * fromStream.Height / fromStream.Width;
Image newImage = new Bitmap(width, newHeight);
using (Graphics graphicsHandle = Graphics.FromImage(newImage))
{
graphicsHandle.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphicsHandle.DrawImage(fromStream, 0, 0, width, newHeight);
}
string processedFileName = String.Concat(Configuration.CoverLocalPath, #"\Processed\res_", Path.GetFileName(imageFile));
newImage.Save(processedFileName, ImageFormat.Jpeg);
newImage.Dispose();
return processedFileName;
}
catch (Exception ex)
{
Configuration.Log.Debug("Utility.cs", "ResizeMainCover", ex.Message);
return string.Empty;
}
I tried to dispose the Image object but without success. Any hints?
Without more code, its hard to tell, but more than likely the culprit is your fromStream not being closed and disposed properly. I'm assuming "previously created" means your source stream. Try wrapping it in a using statement, note I also wrapped the newImage so it would be disposed properly in case of an Exception.
using(var fromStream = GetSourceImageStream())
{
try
{
int newHeight = width * fromStream.Height / fromStream.Width;
using(Image newImage = new Bitmap(width, newHeight))
{
using (Graphics graphicsHandle = Graphics.FromImage(newImage))
{
graphicsHandle.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphicsHandle.DrawImage(fromStream, 0, 0, width, newHeight);
}
string processedFileName = String.Concat(Configuration.CoverLocalPath, #"\Processed\res_", Path.GetFileName(imageFile));
newImage.Save(processedFileName, ImageFormat.Jpeg);
}
return processedFileName;
}
catch (Exception ex)
{
Configuration.Log.Debug("Utility.cs", "ResizeMainCover", ex.Message);
return string.Empty;
}
finally
{
fromStream.Close();
}
}

Setting System.Uri from android uri string xamarin

I have a camerapage which takes a picture, resizes it to a thumbnail and saves this resized image to a file locally on the android phone. I then try to send this uri-string to a viewmodel which is supposed to set its ImageSource property from this uri. I am currently unable to load the image from the url.
Here is my code:
In CameraPage(inside Take photo method)
var documentsPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
using (var imageStream = new MemoryStream())
{
await image.CompressAsync(Bitmap.CompressFormat.Jpeg, 40, imageStream);
image.Recycle();
imageBytes = imageStream.ToArray();
var thumbnail =await DependencyService.Get<IPicResizer>().GetResizedImage(imageBytes);
// Temporary file to store the downloaded image
Java.IO.File tmpFile = new Java.IO.File(documentsPath + "/"+fileName + ".jpg");
tmpFile.ParentFile.Mkdirs();
// String path = MediaStore.Images.Media.InsertImage(this.Context.ContentResolver, documentsPath, fileName, ""); //(this.Context.ContentResolver, image, imgName.ToString(), null);
uri = Android.Net.Uri.Parse(tmpFile.Path);
// The FileOutputStream to the temporary file
var fOutStream = new FileOutputStream(tmpFile);
try
{
fOutStream.Write(thumbnail, 0, thumbnail.Length);
fOutStream.Flush();
fOutStream.Close();
DialogService.HideLoading();
DialogService.ShowSuccess("Saved picture at: " + uri.ToString());
}
catch (Java.IO.FileNotFoundException ex)
{
DialogService.ShowError(ex.InnerException.Message);
}
catch (Java.IO.IOException ex)
{
DialogService.ShowError(ex.InnerException.Message);
}
camera.StartPreview();
await App.Current.MainPage.Navigation.PushModalAsync(new InfoPage(imageBytes, tmpFile.AbsolutePath), false);
}
InfoPages view model:
ImageSource Source {get;set;}
public InfoViewModel(byte[] image, string imageUri)
{
if (image != null)
{
_image = image;
imageurl = new Uri("file:///" + imageUri, UriKind.Absolute);
Source = ImageSource.FromUri(imageurl);
}
}
All help is appreciated :)

System.IO.IOException: The process cannot access the file being used by System.IO.__Error.WinIOError

Problem: First, My "Create" controller action method creates two files two different ways. However, my program is then unable to delete the file which was created using file.SaveAs(path);
I can however successfully delete the other file which was created using
imgPhoto.Save(smallImageFilePath, System.Drawing.Imaging.ImageFormat.Jpeg);
Here is the HttpPost overload of my Create controller action method including a ScaleByPercent method call: (full error message pasted at bottom)
[HttpPost]
[Authorize]
[ValidateAntiForgeryToken]
public ActionResult Create(HttpPostedFileBase file, Models.Gallery gallerycm)
{
ViewBag.Message = "Testing Gallery File Create";
if (file != null && file.ContentLength > 0)
try
{
string path = Path.Combine(Server.MapPath("~/Images/demo/gallery"),
Path.GetFileName(file.FileName));
//System.IO.File.SetAttributes(path, System.IO.FileAttributes.Normal);
//System.Drawing.Image MainImgPhotoVert = System.Drawing.Image.FromFile(path);
/*
System.Drawing.Image MainImgPhotoVert = System.Drawing.Image.FromStream(System.IO.Stream file);
Bitmap MainImgPhoto = (System.Drawing.Bitmap)ScaleByPercent(MainImgPhotoVert, 100);
MainImgPhoto.Save(path, System.Drawing.Imaging.ImageFormat.Jpeg);
MainImgPhoto.Dispose();
*/
file.SaveAs(path);
file.InputStream.Flush(); //useless
file.InputStream.Close(); //less than useless
file.InputStream.Dispose(); //complete waste of keystrokes
//System.IO.File.SetAttributes(path, System.IO.FileAttributes.Normal);
// Validating whether the following commented code releases a recently created
// file from IIS for file Delete. Problem occuring in the Visual Studio test environment.
//file.InputStream.Dispose();
//GC.Collect();
//GC.WaitForPendingFinalizers();
// Create the Thumbnail image
string smallImageFilePath = Path.Combine(Server.MapPath("~/Images/demo/gallery/") + "ThumbSize" + (file.FileName));
//allocate an Image object from the uploaded full sized .jpg
System.Drawing.Image imgPhotoVert = System.Drawing.Image.FromFile(path);
Bitmap imgPhoto = (System.Drawing.Bitmap)ScaleByPercent(imgPhotoVert, 50);
imgPhoto.Save(smallImageFilePath, System.Drawing.Imaging.ImageFormat.Jpeg);
imgPhoto.Dispose();
var gallery = new Gallery();
//gallery.PhotoNumberID = 9;
gallery.Filename = file.FileName;
if (gallerycm.PhotoDescription == null)
gallerycm.PhotoDescription = " ";
gallery.PhotoDescription = gallerycm.PhotoDescription;
var galleryContext = new EFDbGalleryContext();
galleryContext.Gallery.Add(gallery);
galleryContext.SaveChanges();
}
catch (Exception ex)
{
TempData["SomeData"] = file.FileName + " Upload exception. The Details follow: " + ex.ToString();
return RedirectToAction("Index");
}
else
{
ViewBag.Message = "You have not specified a file.";
}
TempData["SomeData"] = "Photo was successfully Added";
return RedirectToAction("Index");
}
static System.Drawing.Image ScaleByPercent(System.Drawing.Image imgPhoto, int Percent)
{
float nPercent = ((float)Percent / 100);
int sourceWidth = imgPhoto.Width;
int sourceHeight = imgPhoto.Height;
int sourceX = 0;
int sourceY = 0;
int destX = 0;
int destY = 0;
int destWidth = (int)(sourceWidth * nPercent);
int destHeight = (int)(sourceHeight * nPercent);
Bitmap bmPhoto = new Bitmap(destWidth, destHeight,
System.Drawing.Imaging.PixelFormat.Format24bppRgb);
bmPhoto.SetResolution(imgPhoto.HorizontalResolution,
imgPhoto.VerticalResolution);
Graphics grPhoto = Graphics.FromImage(bmPhoto);
grPhoto.InterpolationMode =
System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
grPhoto.DrawImage(imgPhoto,
new Rectangle(destX, destY, destWidth, destHeight),
new Rectangle(sourceX, sourceY, sourceWidth, sourceHeight),
GraphicsUnit.Pixel);
grPhoto.Dispose();
return bmPhoto;
}
}
Here is an excerpt from my Delete controller action:
//Delete small and large files from the FileSystem
System.IO.File.Delete(smallImageFilePath);
//System.IO.File.GetAccessControl(largeImageFilePath);
try
{
System.IO.File.GetAccessControl(largeImageFilePath); // Does not help
System.IO.File.Delete(largeImageFilePath);
}
catch (System.IO.IOException e)
{
TempData["SomeData"] = " Delete exception. The Details follow: " + e.ToString();
return RedirectToAction("Index");
}
Note also:
If I pause the program in VS Debug I am able to delete the Bitmap file in Windows Explorer but the other returns:
"File in Use"
"The Action can't be completed because the File is Open in IIS Worker Process. Close the File and Try Again."
If I close VS and go back in I can delete it, but that doesn't help me when I deploy everything on my Godaddy server.
Here is the total message:
Delete exception. The Details follow: System.IO.IOException: The process cannot access the file 'C:\aspnet4_cs\Pettigoats\Pettigoats\Images\demo\gallery\WalkingOnPorch.jpg' because it is being used by another process. at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) at System.IO.File.InternalDelete(String path, Boolean checkHost) at System.IO.File.Delete(String path) at Pettigoats.Controllers.CMAdminController.Delete(Int32 id) in c:\aspnet4_cs\Pettigoats\Pettigoats\Controllers\CMAdminController.cs:line 53
GDI+ puts a lock on the file, for more info GDI+ Graphics
a Dispose() after the save might do the trick

How can I generate a Image in ScheduledAgent?

I'm unsure on how I can go from WriteAbleBitmap to IconicTileData's url property IconImage.
Here is my code so far:
protected override void OnInvoke(ScheduledTask task)
{
ShellTile tile = ShellTile.ActiveTiles.FirstOrDefault();
if (tile != null)
{
WriteableBitmap genTile = renderTile(202, 202);
tile.Update(new IconicTileData()
{
Title = "IconicTileData",
IconImage = /* PATH TO genTile */
});
}
ScheduledActionService.LaunchForTest(task.Name, TimeSpan.FromSeconds(3));
NotifyComplete();
}
private WriteableBitmap renderTile(int width, int height)
{
Canvas can = new Canvas();
can.Background = new SolidColorBrush(Color.FromArgb(255, 0, 255, 0));
can.Width = width;
can.Height = height;
WriteableBitmap tileImage = new WriteableBitmap(width, height);
tileImage.Render(can, null);
tileImage.Invalidate();
return tileImage;
}
The solution would be to save the file? How can I do that, ShellTile does not share the same space as the application?
Save the file to isolated storage, and then use the "isostore:" prefix in the Uri.
public static void StoreSavedResultImage(string filename, WriteableBitmap wb)
{
using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
{
if (isf.FileExists(filename))
isf.DeleteFile(filename);
using (IsolatedStorageFileStream fs = isf.CreateFile(filename))
{
wb.SaveJpeg(fs, wb.PixelWidth, wb.PixelHeight, 0, 100);
fs.Close();
wb = null;
img = null;
}
}
}
If you want to reference a file from isolated storage in a live tile, the file should be saved in the /Shared/ShellContent folder.
Uri wideUri = new Uri("isostore:/Shared/ShellContent/app_wide.jpg"), UriKind.Absolute);
tile.Update(new IconicTileData()
{
Title = "IconicTileData",
IconImage = wideUri
});

Categories

Resources