I have the following method which resizes a given image and caches it
[OutputCache(Duration = 3600, VaryByParam = "id")]
public ActionResult UserFace(int id)
{
var cacheKey = String.Format("userPhotoURICacheKey_{0}", id);
var defaultFileCacheKey = String.Format("userPhotoDefaultCacheKey");
HttpContext.Cache[cacheKey] = HttpContext.Cache[cacheKey] ?? UserService.GetPhotoURI(id) ?? string.Empty;
var userPhoto = (String)HttpContext.Cache[cacheKey];
if (!string.IsNullOrEmpty(userPhoto))
{
var filename = id + ".jpg";
//crop and resize
var image = Image.FromFile(new Uri(userPhoto).LocalPath);
const int resW = 200;
const int resH = 200;
var minEdge = Math.Min(image.Width, image.Height);
var scaleFactor =(float) minEdge/Math.Min(resH, resW);
var newImage = new Bitmap(resW, resH);
var sufrace = Graphics.FromImage(newImage);
sufrace.InterpolationMode = InterpolationMode.HighQualityBicubic;
sufrace.DrawImage(image, 0, 0, image.Width / scaleFactor, image.Height / scaleFactor);
var stream = new MemoryStream();
newImage.Save(stream, ImageFormat.Jpeg);
stream.Position = 0;
var file = File(stream, "image/jpg", filename);
return file;
}
HttpContext.Cache[defaultFileCacheKey] = HttpContext.Cache[defaultFileCacheKey] ?? File("~/Content/images/no_photo.jpg", "image/jpg", "nophoto.jpg");
return (FileResult)HttpContext.Cache[defaultFileCacheKey];
}
In another method I'm trying to update a cached image with a new one
public void UploadUserImage(byte[] arr, int userId)
{
Stream stream = new MemoryStream();
stream.Write(arr, 0, arr.Length);
using (var dataManager = factory.GetDataManager())
{
var userRepository = dataManager.GetRepository<IUserRepository>();
var user = GetByID(userId);
user.PhotoURI =
storageFactory.CreateFileStorageSender()
.Send(storageConfig.UsersPhotoPath, user.Id.ToString(), stream);
user.PhotoSize = stream.Length;
userRepository.Save(user);
dataManager.Commit();
}
}
And I'm getting "The process cannot access the file because it is being used by another process" error.
Dispose image after you're done with resize to use it again.