Graphics object to image file

前端 未结 3 2018
说谎
说谎 2020-12-06 11:56

I would like to crop and resize my image. Here is my code:

Image image = Image.FromFile(AppDomain.CurrentDomain.BaseDirectory + \"Cropper/tests/castle.jpg\")         


        
3条回答
  •  有刺的猬
    2020-12-06 12:03

    This is not a direct answer to the OP's question, but it is an often-overlooked tool that can allow you to approach things in a different way, should that prove necessary.

    It is often said that it's not possible to get at the content of a Graphics object. This is not true at all. With the right approach you can access data on a canvas using HDC and BitBlt. Here is one way to do it using C#:

        enum TernaryRasterOperations : uint
        {
            /// dest = source
            SRCCOPY = 0x00CC0020,
            /// dest = source OR dest
            SRCPAINT = 0x00EE0086,
            /// dest = source AND dest
            SRCAND = 0x008800C6,
            /// dest = source XOR dest
            SRCINVERT = 0x00660046,
            /// dest = source AND (NOT dest)
            SRCERASE = 0x00440328,
            /// dest = (NOT source)
            NOTSRCCOPY = 0x00330008,
            /// dest = (NOT src) AND (NOT dest)
            NOTSRCERASE = 0x001100A6,
            /// dest = (source AND pattern)
            MERGECOPY = 0x00C000CA,
            /// dest = (NOT source) OR dest
            MERGEPAINT = 0x00BB0226,
            /// dest = pattern
            PATCOPY = 0x00F00021,
            /// dest = DPSnoo
            PATPAINT = 0x00FB0A09,
            /// dest = pattern XOR dest
            PATINVERT = 0x005A0049,
            /// dest = (NOT dest)
            DSTINVERT = 0x00550009,
            /// dest = BLACK
            BLACKNESS = 0x00000042,
            /// dest = WHITE
            WHITENESS = 0x00FF0062,
            /// 
            /// Capture window as seen on screen.  This includes layered windows 
            /// such as WPF windows with AllowsTransparency="true"
            /// 
            CAPTUREBLT = 0x40000000
        }
    
        [DllImport("gdi32.dll", EntryPoint = "BitBlt", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        static extern bool BitBlt([In] IntPtr hdc, int nXDest, int nYDest, int nWidth, int nHeight, [In] IntPtr hdcSrc, int nXSrc, int nYSrc, TernaryRasterOperations dwRop);
    
        public static Bitmap CopyGraphicsContent(Graphics source, Rectangle rect)
        {
            Bitmap bmp = new Bitmap(rect.Width, rect.Height);
    
            using (Graphics dest = Graphics.FromImage(bmp))
            {
                IntPtr hdcSource = source.GetHdc();
                IntPtr hdcDest = dest.GetHdc();
    
                BitBlt(hdcDest, 0, 0, rect.Width, rect.Height, hdcSource, rect.X, rect.Y, TernaryRasterOperations.SRCCOPY);
    
                source.ReleaseHdc(hdcSource);
                dest.ReleaseHdc(hdcDest);
            }
    
            return bmp;
        }
    

提交回复
热议问题