I'm facing an issue (ghost border) when an image is resized on the live server, but not on localhost. This is really weird. I did some research on web and found similar solutions:
- https://mariusschulz.com/blog/preventing-ghost-borders-when-resizing-images-with-system-drawing
- https://www.codeproject.com/Articles/11143/Image-Resizing-outperform-GDI
- Ghost-borders ('ringing') when resizing in GDI+
Below is the code that I'm using, inside I have commented old code and new code.
protected byte[] ApplyResize(byte[] byteArray, int targetSize, Size originalSize = default(Size))
{
using (MemoryStream ms = new MemoryStream(byteArray))
{
if (targetSize <= 0)
{
targetSize = 800;
}
var image = Image.FromStream(ms);
var size = default(Size);
if (originalSize != default(Size))
{
size = CalculateDimensions(originalSize, targetSize);
}
else
{
size = new Size(targetSize, targetSize);
}
var resized = new Bitmap(size.Width, size.Height);
using (var graphics = Graphics.FromImage(resized))
{
//old code
//graphics.CompositingQuality = CompositingQuality.HighSpeed;
//graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
//graphics.CompositingMode = CompositingMode.SourceCopy;
//graphics.DrawImage(image, 0, 0, size.Width, size.Height);
//new code
graphics.CompositingQuality = CompositingQuality.HighSpeed;
graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphics.CompositingMode = CompositingMode.SourceCopy;
var attributes = new ImageAttributes();
attributes.SetWrapMode(WrapMode.TileFlipXY);
var destination = new Rectangle(0, 0, size.Width, size.Height);
graphics.DrawImage(image, destination, 0, 0, size.Width, size.Height, GraphicsUnit.Pixel, attributes);
}
using (var ms2 = new MemoryStream())
{
resized.Save(ms2, image.RawFormat);
return ms2.ToArray();
}
}
}
I tested on the live server, yes, the ghost border is gone, but the image has gotten a wrong position.
This image is the expected result after resize, all clear, no problem
This is what happens on localhost and live server, when using the new code, image gets cut with weird position