Skip to content

Instantly share code, notes, and snippets.

@joshi-kumar
Created February 17, 2018 11:33
Show Gist options
  • Save joshi-kumar/e209152e8bf9f8df4a45e19d0a39707e to your computer and use it in GitHub Desktop.
Save joshi-kumar/e209152e8bf9f8df4a45e19d0a39707e to your computer and use it in GitHub Desktop.
Save image and resize image
public string SavePictureApiPath(string mimeType, int productId, byte[] pictureBinary)
{
//string lastPart = GetFileExtensionFromMimeType(mimeType);
string lastPart = "jpg";
string fileName = string.Format("{0}.{1}",productId, lastPart);
string path = Path.Combine(CommonHelper.MapPath("~/reader/new-epubs/coverpage/"), fileName);
byte[] resizePictureBinary;
ReSizeImage(pictureBinary, 550, productId, out resizePictureBinary);
File.WriteAllBytes(path, resizePictureBinary);
return null;
}
private void ReSizeImage(byte[] pictureBinary, int targetSize, int productId ,out byte[] resizePictureBinary)
{
using (var stream = new MemoryStream(pictureBinary))
{
Bitmap b = null;
try
{
//try-catch to ensure that picture binary is really OK. Otherwise, we can get "Parameter is not valid" exception if binary is corrupted for some reasons
b = new Bitmap(stream);
}
catch (ArgumentException exc)
{
_logger.Error(string.Format("Error generating picture thumb. ID={0}", productId),
exc);
}
if (b == null)
{
//bitmap could not be loaded for some reasons
}
using (var destStream = new MemoryStream())
{
var newSize = CalculateDimensions(b.Size, targetSize);
ImageBuilder.Current.Build(b, destStream, new ResizeSettings
{
Width = newSize.Width,
Height = newSize.Height,
Scale = ScaleMode.Both,
Quality = _mediaSettings.DefaultImageQuality
});
resizePictureBinary = destStream.ToArray();
b.Dispose();
}
}
}
protected virtual Size CalculateDimensions(Size originalSize, int targetSize,
ResizeType resizeType = ResizeType.LongestSide, bool ensureSizePositive = true)
{
float width, height;
switch (resizeType)
{
case ResizeType.LongestSide:
if (originalSize.Height > originalSize.Width)
{
// portrait
width = originalSize.Width * (targetSize / (float)originalSize.Height);
height = targetSize;
}
else
{
// landscape or square
width = targetSize;
height = originalSize.Height * (targetSize / (float) originalSize.Width);
}
break;
case ResizeType.Width:
width = targetSize;
height = originalSize.Height * (targetSize / (float)originalSize.Width);
break;
case ResizeType.Height:
width = originalSize.Width * (targetSize / (float)originalSize.Height);
height = targetSize;
break;
default:
throw new Exception("Not supported ResizeType");
}
if (ensureSizePositive)
{
if (width < 1)
width = 1;
if (height < 1)
height = 1;
}
//we invoke Math.Round to ensure that no white background is rendered - http://www.nopcommerce.com/boards/t/40616/image-resizing-bug.aspx
return new Size((int)Math.Round(width), (int)Math.Round(height));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment