Click here to Skip to main content
14,699,613 members
Please Sign up or sign in to vote.
2.00/5 (3 votes)
See more:
I want to crop image using pixels...

additional information copied from non-solution below
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using ComponentFactory.Krypton.Toolkit;
using System.IO;

namespace imageconverter1
    public partial class frmimage : ComponentFactory.Krypton.Toolkit.KryptonForm
        public frmimage()

        #region Declaration
        int LValue, HValue;
        String Path;

        #region Method
        #region FillDiamondType
        public void FillDiamondType()
            cmbDiamondType.Items.Add("--Select Diamon Type--");
            cmbDiamondType.SelectedIndex = 0;

        #region ChangeColor
        public static Bitmap ChangeColor(Bitmap scrBitmap, int Lvalue, int Hvalue)

            //int start = 0, End = 0;
            //You can change your new color here. Red,Green,LawnGreen any..
            Color newColor = Color.Red;
            Color actulaColor = Color.FromArgb(0, 0, 0, 0);
            //make an empty bitmap the same size as scrBitmap
            Bitmap newBitmap = new Bitmap(scrBitmap.Width, scrBitmap.Height);
            Color cmpcolor = scrBitmap.GetPixel(10, 10);

            for (int i = 0; i < scrBitmap.Width; i++)
                for (int j = 0; j < scrBitmap.Height - 3; j++)

                    actulaColor = scrBitmap.GetPixel(i, j);
                    if (((actulaColor.B <= cmpcolor.B + Lvalue) && (actulaColor.B >= (cmpcolor.R - Hvalue)))
                        && ((actulaColor.R <= cmpcolor.R + Lvalue) && (actulaColor.R >= (cmpcolor.R - Hvalue)))
                        && ((actulaColor.G <= cmpcolor.G + Lvalue) && (actulaColor.G >= (cmpcolor.G - Hvalue))))

                        //if (j <= scrBitmap.Height / 2)
                        //    start = j;
                        newBitmap.SetPixel(i, j, newColor);
                        // End = j;
                        newBitmap.SetPixel(i, j, actulaColor);

                //for (int k = start; k <= End; k++)
                //    chk1 = scrBitmap.GetPixel(i,k);
                //    newBitmap.SetPixel(i, k, chk1);


            return newBitmap;

        #region Event

        #region frmimage_Load
        private void frmimage_Load(object sender, EventArgs e)
            //Fill item in Diamond type


        #region btnloadPhoto_Click
        private void btnloadPhoto_Click(object sender, EventArgs e)
                OpenFileDialog open = new OpenFileDialog();
                // image filters

                open.Filter = "Image Files(*.jpg; *.jpeg; *.gif; *.bmp)|*.jpg; *.jpeg; *.gif; *.bmp";
                if (open.ShowDialog() == DialogResult.OK)
                    // display image in picture box
                    pictureBox1.Image = new Bitmap(open.FileName);

                    Image image = Image.FromFile(open.FileName);
                    // Set the PictureBox image property to this image.
                    // ... Then, adjust its height and width properties.
                    pictureBox1.Visible = true;
                    pictureBox1.Image = image;
                    pictureBox1.Height = image.Height;
                    pictureBox1.Width = image.Width;
                    Path = open.FileName;
                    pictureBox2.Image = image;
                    pictureBox2.Height = image.Height;
                    pictureBox2.Width = image.Width;
                    pictureBox2.Image = null;
                    // image file path

            catch (Exception ex)
                KryptonMessageBox.Show(ex.Message, "Converter", MessageBoxButtons.OK, MessageBoxIcon.Error);
        #region btnconvert_Click
        private void btnconvert_Click(object sender, EventArgs e)

                if (cmbDiamondType.SelectedIndex == 0)
                    KryptonMessageBox.Show("Select Diamond Type", "Diamond", MessageBoxButtons.OK, MessageBoxIcon.Warning);

                Bitmap mypic = (Bitmap)Image.FromFile(Path);
                int imwid = mypic.Width;
                int imhei = mypic.Height;
                int total = imwid * imhei;

                if (pictureBox2.Image != null)
                Bitmap NEWPIC = new Bitmap(imwid, imhei);
                NEWPIC = ChangeColor(mypic, LValue, HValue);

                pictureBox2.Visible = true;
                pictureBox2.Image = new Bitmap(NEWPIC);

            catch (Exception ex)
                KryptonMessageBox.Show(ex.Message, "Converter", MessageBoxButtons.OK, MessageBoxIcon.Error);
        #region btnCOnvertAll_Click
        private void btnCOnvertAll_Click(object sender, EventArgs e)

                Bitmap bmp = null;
                //The Source Directory in debug\bin\Big\
                string[] files = Directory.GetFiles("Big\\");
                foreach (string filename in files)
                    bmp = (Bitmap)Image.FromFile(filename);
                    bmp = ChangeColor(bmp, LValue, HValue);
                    string[] spliter = filename.Split('\\');
                    //Destination Directory debug\bin\BigGreen\
                    bmp.Save("BigGreen\\" + spliter[1]);

            catch (Exception ex)
                KryptonMessageBox.Show(ex.Message, "Converter", MessageBoxButtons.OK, MessageBoxIcon.Error);

        #region cmbDiamondType_KeyPress
        private void cmbDiamondType_KeyPress(object sender, KeyPressEventArgs e)
            if ((int)(e.KeyChar) == 13)


        private void cmbDiamondType_SelectedIndexChanged(object sender, EventArgs e)
            if (cmbDiamondType.SelectedIndex == 1)
                LValue = 2; HValue = 3;
            if (cmbDiamondType.SelectedIndex == 2)
                LValue = 15; HValue = 15;
            if (cmbDiamondType.SelectedIndex == 3)
                LValue = 22; HValue = 20;


        private void btnBack_Click(object sender, EventArgs e)
            btnconvert_Click(sender, e);

        private void btnfrd_Click(object sender, EventArgs e)
            btnconvert_Click(sender, e);



//But Some problem in it i loss Some actual pixel into the image
Updated 21-Nov-14 12:51pm
BillWoodruff 21-Nov-14 12:08pm
Why did you specify "pixels" ?
King Fisher 21-Nov-14 23:28pm
You want to resize the image?

Try this link,

Or try this code,
string filename = Path.GetFileName(Fileupd1.PostedFile.FileName);                 

System.Drawing.Image UploadedImage = System.Drawing.Image.FromStream(Fileupd1.PostedFile.InputStream);
float UploadedImageWidth = UploadedImage.PhysicalDimension.Width;
float UploadedImageHeight = UploadedImage.PhysicalDimension.Height;
if (UploadedImageHeight >= 450 && UploadedImageWidth >= 600) //Here you can limit the size
string targetPath = Server.MapPath("../Upload/" + filename);
Stream strm = Fileupd1.PostedFile.InputStream;
var targetFile = targetPath;
//Based on scalefactor image size will vary
GenerateThumbnails(0.8, strm, targetFile);
Fileupd1.PostedFile.SaveAs(Server.MapPath("../Upload/" + filename));

private void GenerateThumbnails(double scaleFactor, Stream sourcePath, string targetPath)
using (var image = System.Drawing.Image.FromStream(sourcePath))
// can given width of image as we want
//var newWidth = (int)(image.Width * scaleFactor);
var newWidth = 600;// can given height of image as we want
//var newHeight = (int)(image.Height * scaleFactor);
var newHeight = 450;
var thumbnailImg = new Bitmap(newWidth, newHeight);
var thumbGraph = Graphics.FromImage(thumbnailImg);
thumbGraph.CompositingQuality = CompositingQuality.HighQuality;
thumbGraph.SmoothingMode = SmoothingMode.HighQuality;
thumbGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;
var imageRectangle = new Rectangle(0, 0, newWidth, newHeight);
thumbGraph.DrawImage(image, imageRectangle);
thumbnailImg.Save(targetPath, image.RawFormat);

Hope it'll helpfull to you,

BillWoodruff 21-Nov-14 12:03pm
If this is not code you wrote, please post a link to the source.
Rajesh waran 21-Nov-14 23:19pm
Ok sir,let me continue my further solution with your suggestion. Thank you sir.
BillWoodruff 22-Nov-14 8:57am
It's always a good practice to cite your sources, if what you post is not original; if you wrote an article on CP and someone posted your code as part of an answer, wouldn't you appreciate their acknowledging your effort ? And, of course, if you are posting code from a copyrighted source, it becomes more important to cite.

However, if you've taken code from someplace on the web ... which we all do ... and modified it, adapted it, tested it, so that it has become your "own:" well, even in that case it doesn't hurt to cite your source. In other words one doesn't have to be "fanatic" about this.

Also, if posting complex code, it's a very good thing to say if you have tried the code yourself. Unless the code comes from people (on StackOverFlow) like Jon Skeet, or Eric Lippert, or Marc Gravell, or (on CP), from OriginalGriff, or Marc Clifton, or Richard MacCutchan, or Richard Deeming ... or someone you really know is a top-level programmer ...
Rajesh waran 24-Nov-14 0:13am
ok sir, i can understand.i'll take this on mind when posting next solution in CP. Thank you for the valuable advise.
This is from working code I wrote a few years ago:
private Bitmap CreateCroppedBitmap(Bitmap sourceBmp, Point sourcePoint, Rectangle cropRect)
    // make sure you are using the right value here !
    GraphicsUnit gu = GraphicsUnit.Point;

    // prepare the target rectangle to be used as the crop source
    RectangleF sourceRect = sourceBmp.GetBounds(ref gu);
    sourceRect.X += sourcePoint.X;
    sourceRect.Y += sourcePoint.Y;
    sourceRect.Height = cropRect.Height;
    sourceRect.Width = cropRect.Width;

    // where to draw the copied-from-source bitmap
    // in the new bitmap
    // upper-left, upper-right, lower-left
    PointF[] pointFAry = new PointF[]
        new PointF(0, 0),
        new PointF(cropRect.Width, 0),
        new PointF(0, cropRect.Height)

    // get a new Bitmap sized to crop size
    Bitmap imageCrop = new Bitmap(cropRect.Width,cropRect.Height);

    // get the handle to its graphics
    Graphics gr = Graphics.FromImage(imageCrop);

    // draw the selected area of the source bitmap
    // into the new bitmap
    gr.DrawImage(sourceBmp, pointFAry, sourceRect, gu);

    return imageCrop;
Here's a sample of using it to get the BackGroundImage in a PictureBox, and create a cropped image that is then set to be the BackGroundImage of a second PictureBox: (this was re-tested today using .NET 4.5 in Visual Studio 2013)
private void PerformCrop(object sender, EventArgs e)
    Bitmap croppedImage = CreateCroppedBitmap(
        (Bitmap) pbxSource.Image, 
        new Point(200,200), 

    // test   
    pbxDestination.BackgroundImage = croppedImage;
Note that this code is hard-coded to use 'Point as the GraphicsUnit. In this example the crop is the same size as the PictureBox that the cropped bitmap is inserted into, and the crop upper-left is located at 200,200 in the source bitmap.
You can do that using the Bitmap[^] object. Create a Bitmap object using your image file, and create the graphics[^] for the co-ordinates you want to get.
BillWoodruff 21-Nov-14 12:05pm
My vote of #1: This is like saying to someone who who asks you how use an ATM machine: go to the Bank. You are too bright to abuse CP with posts like this which show no effort to understand the OP's goal, or reach it.
0x01AA 21-Nov-14 18:31pm
Why not simply make the comment and be neutral in voting?
If it goes like this, nobody than you and some other high pointed members dare to write a reply...same I faced a lot of time...trying to help (yes most probably not perfect) and downvote!!!!
If this should be the future then CP should allow only members with bigger X Points to answer a question.

Now you can search to some of my answers and downvote them.
King Fisher 22-Nov-14 1:50am
absolutely, but many members answer a question to earn points in CP. how do we block this ?
Afzaal Ahmad Zeeshan 22-Nov-14 2:41am
The members who answer a question to earn points; suppose +10 would get continously losing their points; -16. :-) So don't worry. :)
Afzaal Ahmad Zeeshan 22-Nov-14 2:48am
Things happen Bruno. :-)

Usually, I've seen my posts down-voted for having entire source code in them, or for being just a tip like this one.

Everyone has right to vote (up or down). :-) So need to worry. Also, yesterday there was another havoc in my rep history a bunch of downvotes! :D

CP really has a great source of experts, I have been on Stack Overflow, Official ASP.NET forums and many other places, the ratio of experts to newbies is really high on CodeProject, that is why they require you to be the perfect answerer. :-)

Bill, is a nice helper, and he would surely want others to help out people too. :)
Afzaal Ahmad Zeeshan 22-Nov-14 2:44am
I believe I should tell that guy to go to bank, because atleast on the ATM machine the steps of using it are mentioned fair, 1) Enter your card, 2) Enter your pin code, 3) Enter amount of deduct, 4) Press 1 for transaction.

Now think of this, a guy comes to me and I start telling him the same thing that he can read from the machine on the go. Would that be a standard?

I accept that vote of 1, for you my answer doesn't fit as a standard? I will make it a fit, no need to rebel. :-)
0x01AA 21-Nov-14 18:50pm
My vote of 5 even it Counts only lim->0
at least I was not so cowardly and have voted anonymously!
Afzaal Ahmad Zeeshan 22-Nov-14 2:40am
Thanks for you 5 Bruno. :-)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900