Измените размер изображения 2x2 пикселей, чтобы он соответствовал 4x4 пикселям, сохраняя цвета одинаковыми - PullRequest
1 голос
/ 04 февраля 2012

Пожалуйста, представьте, что у меня очень простое изображение на шахматной доске.

Здесь я представляю изображение с буквами в виде пикселей: черный пиксель «B», белый пиксель «W»

Вот начальное 2x2 пиксельное изображение:

BW
WB

Я хочу изменить размер изображения, скажем, в 2 раза, чтобы дать мне:

BBWW
BBWW
WWBB
WWBB

или шкала 4x

BBBBWWWW
BBBBWWWW
WWWWBBBB
WWWWBBBB

Так что цвета пикселей вообще никак не размываются.

Я пробовал это в C #, но изображение беспорядок, все размыто, мне нужно научиться делать это без сглаживания / изменения цвета.

Вот мой код:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Text;

namespace PageTwine
{
    public partial class RandonGiff : System.Web.UI.Page
    {


        protected void Page_Load(object sender, EventArgs e)
        {

            // create 2x2 chequerboard:
            Bitmap oBitmap = new Bitmap(2, 2);
            Graphics oGraphic = Graphics.FromImage(oBitmap);

            // color black pixels (i think the default is black but this helps to explain)
            SolidBrush oBrush = new SolidBrush(Color.FromArgb(255, 255, 255));
            oGraphic.FillRectangle(oBrush, 0, 0, 1, 1);
            oGraphic.FillRectangle(oBrush, 1, 1, 1, 1);

            //color white pixels
            oBrush = new SolidBrush(Color.FromArgb(0, 0, 0));
            oGraphic.FillRectangle(oBrush, 0, 1, 1, 1);
            oGraphic.FillRectangle(oBrush, 1, 0, 1, 1);

            // expand to 4x4
            Bitmap result = new Bitmap(4, 4);
            using (Graphics graphics = Graphics.FromImage(result))
            {
                // I don't know what these settings should be :

                graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.NearestNeighbor;
                graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.None;

                //draw the image into the target bitmap 
                graphics.DrawImage(oBitmap, 0, 0, result.Width, result.Height);
            }

            //send image directly to the browser
            Response.ContentType = "image/gif";
            result.Save(Response.OutputStream, ImageFormat.Gif);

        }
    }

}

В результате получается размытое изображение, но мне нужен чистый четкий эффект chequerboard. Пожалуйста, вы можете мне помочь.

EDIT: 07/02/12

Спасибо за предложения, но я все еще ищу, не найдя решения.

Я создал демонстрационную страницу, чтобы вы могли сами увидеть результаты.

URL для демонстрации:

http://www.leansoftware.net/servicedesk/publicadhoc/randomgif.aspx?columns=3&rows=3

Демонстрация создаст шахматную доску с начальными столбцами x строками в виде пикселей, а затем увеличится до gif изображения 300x300 пикселей.

Вы увидите, что цвета искажены / горькие - это я пытаюсь решить.

Вот исходный код демо:

using System;
using System.Collections.Generic;
using System.Web;
using System.IO;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Text;
using System.Linq;


    public partial class RandomGif : System.Web.UI.Page
    {
        public class Coordinates
        {
            public int x { get; set; }
            public int y { get; set; }
        }

        static Random rand = new Random();

        protected void Page_Load(object sender, EventArgs e)
        {
            // Output type gif
            int iwidth;
            int iheight;
            int bits;
            Response.ContentType = "image/gif";

            // Get parameters
            if (Request.QueryString["count"] != null)
            {
                bits = Convert.ToInt32(Request.QueryString["count"]);
                int square = Convert.ToInt32(Math.Ceiling(Math.Sqrt(bits + Math.Floor(bits / 4.0))));
                iwidth = square;
                iheight = square;
                bits = (square * square)-1;
            }
            else
                if (Request.QueryString["rows"] != null && Request.QueryString["columns"] != null)
                {
                    iwidth = Convert.ToInt32(Request.QueryString["columns"]);
                    iheight = Convert.ToInt32(Request.QueryString["rows"]);
                    bits = (iwidth * iheight);
                }
                else {
                    return;
                }
        if (bits > 1000){
        Response.Write("Please specify a grid <= 1000 pixels");
        return;
        }

            int plotCount = 0;

            //web safe colors : 00, 33, 66, 99, CC, FF;
            List<int> webSafeColor = new List<int>();
            webSafeColor.Add(0); //00
            webSafeColor.Add(51);//33
            webSafeColor.Add(102);//66
            webSafeColor.Add(153);//99
            webSafeColor.Add(204);//CC
            webSafeColor.Add(255);//FF

            // Create a structure to hold all possible coordinates
            var Grid = new List<Coordinates>();
            for (int xi = 1; xi <= iwidth; xi++)
            {
                for (int yi = 1; yi <= iheight; yi++)
                {
                    Grid.Add(new Coordinates { x = xi, y = yi });
                    plotCount++;
                }
            }

            //create a new Bitmap object
            Bitmap oBitmap = new Bitmap(iwidth, iheight);

            //create a new Graphics object, which will allow us to draw on our bitmap:
            Graphics oGraphic = Graphics.FromImage(oBitmap);


            //fill the image rectangle with n bits
            for (int i = 1; i <= bits; i++)
            {
                //Random rand = new Random();
                int row = rand.Next(Grid.Count());

                // random red
                int ircolor = webSafeColor[rand.Next(5)];

                // random green
                int igcolor = webSafeColor[rand.Next(5)];

                // random blue
                int ibcolor = webSafeColor[rand.Next(5)];

                Color randomColor = Color.FromArgb(ircolor, igcolor, ibcolor);
                SolidBrush oBrush = new SolidBrush(randomColor);
                oGraphic.FillRectangle(oBrush, Grid[row].x - 1, Grid[row].y - 1, 1, 1);

        // Delete this coordinate#
                Grid.Remove(Grid[row]);
            }

            // resize image
            Bitmap result = new Bitmap(300, 300);
            using (Graphics graphics = Graphics.FromImage(result))
            {
                //set the resize quality modes to high quality 
                graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.AssumeLinear;
                graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.NearestNeighbor;
                graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
                graphics.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.Half; 

                //draw the image into the target bitmap 
                graphics.DrawImage(oBitmap, 0, 0, result.Width, result.Height);
            }

            //send image directly to the browser
            Response.ContentType = "image/gif";
            result.Save(Response.OutputStream, ImageFormat.Gif);

        }
    }

Если вы можете предложить изменения, мы можем попробовать их и посмотреть, решит ли это проблему.

Спасибо, Ричард

Ответы [ 2 ]

2 голосов
/ 04 февраля 2012

Это возможный дубликат c # Draw Image (Scaled) to Graphics, неправильно интерполируется.Исправления?

Вам необходимо добавить:

graphics.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.Half;

В качестве альтернативы, вы можете использовать

graphics.DrawImage(oBitmap, 0, 0, result.Width * 2, result.Height * 2);

, чтобы добиться аналогичного эффекта, заставляя кисть заполнитьбез деформации по краям правого нижнего края изображения.

Обновление:

Добавление ссылки для создания проиндексированных изображений с пользовательской цветовой палитрой.http://support.microsoft.com/kb/319061

0 голосов
/ 04 февраля 2012

Использование:

System.Drawing.Drawing2D.InterpolationMode.NearestNeighbor;
...