<p>Does anyone have the secret formula to resizing transparent images (mainly GIFs) <em>without</em> ANY quality loss - what so ever?</p>

<p>I've tried a bunch of stuff, the closest I get is not good enough.</p>

<p>Take a look at my main image:</p>

<p><a href="http://www.thewallcompany.dk/test/main.gif" rel="noreferrer">http://www.thewallcompany.dk/test/main.gif</a></p>

<p>And then the scaled image:</p>

<p><a href="http://www.thewallcompany.dk/test/ScaledImage.gif" rel="noreferrer">http://www.thewallcompany.dk/test/ScaledImage.gif</a></p>

<pre><code>//Internal resize for indexed colored images
void IndexedRezise(int xSize, int ySize)
{
  BitmapData sourceData;
  BitmapData targetData;

  AdjustSizes(ref xSize, ref ySize);

  scaledBitmap = new Bitmap(xSize, ySize, bitmap.PixelFormat);
  scaledBitmap.Palette = bitmap.Palette;
  sourceData = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height),
    ImageLockMode.ReadOnly, bitmap.PixelFormat);
  try
  {
    targetData = scaledBitmap.LockBits(new Rectangle(0, 0, xSize, ySize),
      ImageLockMode.WriteOnly, scaledBitmap.PixelFormat);
    try
    {
      xFactor = (Double)bitmap.Width / (Double)scaledBitmap.Width;
      yFactor = (Double)bitmap.Height / (Double)scaledBitmap.Height;
      sourceStride = sourceData.Stride;
      sourceScan0 = sourceData.Scan0;
      int targetStride = targetData.Stride;
      System.IntPtr targetScan0 = targetData.Scan0;
      unsafe
      {
        byte* p = (byte*)(void*)targetScan0;
        int nOffset = targetStride - scaledBitmap.Width;
        int nWidth = scaledBitmap.Width;
        for (int y = 0; y &lt; scaledBitmap.Height; ++y)
        {
          for (int x = 0; x &lt; nWidth; ++x)
          {
            p[0] = GetSourceByteAt(x, y);
            ++p;
          }
          p += nOffset;
        }
      }
    }
    finally
    {
      scaledBitmap.UnlockBits(targetData);
    }
  }
  finally
  {
    bitmap.UnlockBits(sourceData);
  }
}
</code></pre>

<p>I'm using the above code, to do the indexed resizing.</p>

<p>Does anyone have improvement ideas?</p>

[{'answer_id': 30581, 'author': 'Jonathan', 'author_id': 3251, 'author_profile': 'https://Stackoverflow.com/users/3251', 'pm_score': 2, 'selected': False, 'text': '<p>I think the problem is that you\'re doing a scan line-based resize, which is going to lead to jaggies no matter how hard you tweak it.  Good image resize quality requires you to do some more work to figure out the average color of the pre-resized pixels that your resized pixel covers.</p>\n\n<p>The guy who runs this website has a blog post that discusses a few image resizing algorithms.  You probably want a bicubic image scaling algorithm.</p>\n\n<p><a href="http://www.codinghorror.com/blog/archives/000903.html" rel="nofollow noreferrer">Better Image Resizing</a></p>\n'}, {'answer_id': 30582, 'author': 'Dillie-O', 'author_id': 71, 'author_profile': 'https://Stackoverflow.com/users/71', 'pm_score': 3, 'selected': False, 'text': '<p>This is a basic resize function I\'ve used for a few of my applications that leverages GDI+</p>\n\n<pre><code>/// &lt;summary&gt;\n///    Resize image with GDI+ so that image is nice and clear with required size.\n/// &lt;/summary&gt;\n/// &lt;param name="SourceImage"&gt;Image to resize&lt;/param&gt;\n/// &lt;param name="NewHeight"&gt;New height to resize to.&lt;/param&gt;\n/// &lt;param name="NewWidth"&gt;New width to resize to.&lt;/param&gt;\n/// &lt;returns&gt;Image object resized to new dimensions.&lt;/returns&gt;\n/// &lt;remarks&gt;&lt;/remarks&gt;\npublic static Image ImageResize(Image SourceImage, Int32 NewHeight, Int32 NewWidth)\n{\n   System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(NewWidth, NewHeight, SourceImage.PixelFormat);\n\n   if (bitmap.PixelFormat == Drawing.Imaging.PixelFormat.Format1bppIndexed | bitmap.PixelFormat == Drawing.Imaging.PixelFormat.Format4bppIndexed | bitmap.PixelFormat == Drawing.Imaging.PixelFormat.Format8bppIndexed | bitmap.PixelFormat == Drawing.Imaging.PixelFormat.Undefined | bitmap.PixelFormat == Drawing.Imaging.PixelFormat.DontCare | bitmap.PixelFormat == Drawing.Imaging.PixelFormat.Format16bppArgb1555 | bitmap.PixelFormat == Drawing.Imaging.PixelFormat.Format16bppGrayScale) \n   {\n      throw new NotSupportedException("Pixel format of the image is not supported.");\n   }\n\n   System.Drawing.Graphics graphicsImage = System.Drawing.Graphics.FromImage(bitmap);\n\n   graphicsImage.SmoothingMode = Drawing.Drawing2D.SmoothingMode.HighQuality;\n   graphicsImage.InterpolationMode = Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;\n   graphicsImage.DrawImage(SourceImage, 0, 0, bitmap.Width, bitmap.Height);\n   graphicsImage.Dispose();\n   return bitmap; \n}\n</code></pre>\n\n<p>I don\'t remember off the top of my head if it will work with GIFs, but you can give it a try.</p>\n\n<p>Note: I can\'t take full credit for this function. I pieced a few things together from some other samples online and made it work to my needs 8^D</p>\n'}, {'answer_id': 30593, 'author': 'Markus Olsson', 'author_id': 2114, 'author_profile': 'https://Stackoverflow.com/users/2114', 'pm_score': 7, 'selected': True, 'text': '<p>If there\'s no requirement on preserving file type after scaling I\'d recommend the following approach.</p>\n\n<pre><code>using (Image src = Image.FromFile("main.gif"))\nusing (Bitmap dst = new Bitmap(100, 129))\nusing (Graphics g = Graphics.FromImage(dst))\n{\n   g.SmoothingMode = SmoothingMode.AntiAlias;\n   g.InterpolationMode = InterpolationMode.HighQualityBicubic;\n   g.DrawImage(src, 0, 0, dst.Width, dst.Height);\n   dst.Save("scale.png", ImageFormat.Png);\n}\n</code></pre>\n\n<p>The result will have really nice anti aliased edges</p>\n\n<ul>\n<li><em>removed image shack image that had been replaced by an advert</em></li>\n</ul>\n\n<p>If you must export the image in gif you\'re in for a ride; GDI+ doesn\'t play well with gif. See <a href="http://www.ben-rush.net/blog/PermaLink.aspx?guid=103ed74d-c808-47ba-b82d-6e9367714b3e&amp;dotnet=consultant" rel="noreferrer">this blog post</a> about it for more information</p>\n\n<p><strong>Edit:</strong> I forgot to dispose of the bitmaps in the example; it\'s been corrected</p>\n'}, {'answer_id': 870665, 'author': 'Bela', 'author_id': 107932, 'author_profile': 'https://Stackoverflow.com/users/107932', 'pm_score': 1, 'selected': False, 'text': '<p>For anyone that may be trying to use Markus Olsson\'s solution to dynamically resize images and write them out to the Response Stream.</p>\n\n<p>This will not work:</p>\n\n<pre><code>Response.ContentType = "image/png";\ndst.Save( Response.OutputStream, ImageFormat.Png );\n</code></pre>\n\n<p>But this will:</p>\n\n<pre><code>Response.ContentType = "image/png";\nusing (MemoryStream stream = new MemoryStream())\n{\n    dst.Save( stream, ImageFormat.Png );\n\n    stream.WriteTo( Response.OutputStream );\n}\n</code></pre>\n'}, {'answer_id': 10941029, 'author': 'Lilith River', 'author_id': 166893, 'author_profile': 'https://Stackoverflow.com/users/166893', 'pm_score': 0, 'selected': False, 'text': '<p>While PNG is definitely better that GIF, occasionally there is a use case for needing to stay in GIF format. </p>\n\n<p>With GIF or 8-bit PNG, you have to address the problem of quantization.</p>\n\n<p>Quantization is where you choose which 256 (or fewer) colors will best preserve and represent the image, and then turn the RGB values back into indexes. When you perform a resize operation, the ideal color palette changes, as you are mixing colors and changing balances. </p>\n\n<p>For slight resizes, like 10-30%, you may be OK preserving the original color palette. </p>\n\n<p>However, in most instances you\'ll need to re-quantize. </p>\n\n<p>The primary two algorithms to pick from are Octree and nQuant. Octree is very fast and does a very good job, especially if you can overlay a smart dithering algorithm. nQuant requires at least 80MB of RAM to perform an encode (it builds a complete histogram), and is typically 20-30X slower (1-5 seconds per encode on an average image). However, it sometimes produces  higher image quality that Octree since it doesn\'t \'round\' values to maintain consistent performance.</p>\n\n<p>When implementing transparent GIF and animated GIF support in the <a href="http://imageresizing.net" rel="nofollow">imageresizing.net</a> project, I chose Octree. Transparency support isn\'t hard once you have control of the image palette.</p>\n'}]
['https://Stackoverflow.com/questions/30569', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2972/']