如何裁剪图像.... [英] how to crop an image....

查看:88
本文介绍了如何裁剪图像....的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用像素裁剪图片...



从非解决方案复制的其他信息

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()
        {
            InitializeComponent();
        }

        #region Declaration
        int LValue, HValue;
        String Path;
        #endregion

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

        }
        #endregion
        #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);
                    }
                    else
                    {
                        // 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;
        }
        #endregion
        #endregion

        #region Event

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

            FillDiamondType();
            btnloadPhoto.Focus();

        }
        #endregion
        #region btnloadPhoto_Click
        private void btnloadPhoto_Click(object sender, EventArgs e)
        {
            try
            {
                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

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

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

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

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

                pictureBox2.Visible = true;
                pictureBox2.Image = new Bitmap(NEWPIC);
                NEWPIC.Save(@"D:\mahendra\a.png");

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

                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);
            }
        }
        #endregion


        #region cmbDiamondType_KeyPress
        private void cmbDiamondType_KeyPress(object sender, KeyPressEventArgs e)
        {
            if ((int)(e.KeyChar) == 13)
            {
                SendKeys.Send("{tab}");

            }
        }
        #endregion

        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;
            }
        }


        #endregion

        private void btnBack_Click(object sender, EventArgs e)
        {
            LValue--;
            HValue--;
            btnconvert_Click(sender, e);
        }

        private void btnfrd_Click(object sender, EventArgs e)
        {
            LValue++;
            HValue++;
            btnconvert_Click(sender, e);

        }


    }
}



//但是它有些问题我丢失一些实际像素进入图像


//But Some problem in it i loss Some actual pixel into 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);
}
else
{
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);
thumbGraph.Dispose();
}
}





希望它对你有所帮助,



问候,

R @ JE



Hope it'll helpfull to you,

Regards,
R@JE



这是来自我编写的工作代码几年前:
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;
}

下面是一个使用它来获取PictureBox中BackGroundImage的示例,并创建一个裁剪后的图像,然后设置为第二个PictureBox的BackGroundImage :(这是重新测试的今天在Visual Studio 2013中使用.NET 4.5)

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), 
        pbxDestination.DisplayRectangle);

    // test   
    pbxDestination.BackgroundImage = croppedImage;
}

请注意,此代码是硬编码的,使用'Point作为GraphicsUnit。在此示例中,裁剪与插入裁剪位图的PictureBox大小相同,裁剪左上角位于源位图中的200,200。

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.


这篇关于如何裁剪图像....的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆