示例#1
0
        private static bool SaveNonJpeg(Image imageToSave, ImageFormat imageFormat, Stream stream)
        {
            bool needsDispose = false;

            // Removing transparency if it's not supported in the output
            if (imageFormat != ImageFormat.Png && Image.IsAlphaPixelFormat(imageToSave.PixelFormat))
            {
                imageToSave  = ImageOperator.Clone(imageToSave, PixelFormat.Format24bppRgb);
                needsDispose = true;
            }

            try {
                imageToSave.Save(stream, imageFormat);
                return(true);
            }
            catch (Exception ex) {
                log.Error("Failed to save image, " + ex.Message);
                return(false);
            }
            finally {
                if (needsDispose && imageToSave != null)
                {
                    imageToSave.Dispose();
                    imageToSave = null;
                }
            }
        }
示例#2
0
        private Image CreateBorder(Image sourceImage, int borderSize, Color borderColor, PixelFormat targetPixelformat, out Point offset)
        {
            offset = new Point(borderSize, borderSize);

            Bitmap newImage = ImageOperator.CreateEmptyBitmap(sourceImage.Width + (borderSize * 2), sourceImage.Height + (borderSize * 2), targetPixelformat, Color.Empty, sourceImage.HorizontalResolution, sourceImage.VerticalResolution);

            using (Graphics graphics = Graphics.FromImage(newImage)) {
                // Make sure we draw with the best quality!
                graphics.SmoothingMode      = SmoothingMode.HighQuality;
                graphics.PixelOffsetMode    = PixelOffsetMode.HighQuality;
                graphics.CompositingQuality = CompositingQuality.HighQuality;
                graphics.InterpolationMode  = InterpolationMode.HighQualityBicubic;
                using (GraphicsPath path = new GraphicsPath()) {
                    path.AddRectangle(new Rectangle(borderSize >> 1, borderSize >> 1, newImage.Width - (borderSize), newImage.Height - (borderSize)));
                    using (Pen pen = new Pen(borderColor, borderSize)) {
                        pen.LineJoin = LineJoin.Round;
                        pen.StartCap = LineCap.Round;
                        pen.EndCap   = LineCap.Round;
                        graphics.DrawPath(pen, path);
                    }
                }
                // draw original with a TextureBrush so we have nice antialiasing!
                using (Brush textureBrush = new TextureBrush(sourceImage, WrapMode.Clamp)) {
                    // We need to do a translate-tranform otherwise the image is wrapped
                    graphics.TranslateTransform(offset.X, offset.Y);
                    graphics.FillRectangle(textureBrush, 0, 0, sourceImage.Width, sourceImage.Height);
                }
            }
            return(newImage);
        }
示例#3
0
        public static IFastBitmap CreateEmpty(Size newSize, PixelFormat pixelFormat, Color backgroundColor)
        {
            Bitmap      destination = ImageOperator.CreateEmptyBitmap(newSize.Width, newSize.Height, pixelFormat, backgroundColor, 96f, 96f);
            IFastBitmap fastBitmap  = Create(destination);

            fastBitmap.NeedsDispose = true;
            return(fastBitmap);
        }
示例#4
0
        public Image Apply(Image sourceImage, out Point offsetChange)
        {
            offsetChange = Point.Empty;

            RotateFlipType flipType = EffectType == FlipEffectType.HorizontalFlip
                ? RotateFlipType.RotateNoneFlipX : RotateFlipType.RotateNoneFlipY;

            return(ImageOperator.RotateFlip(sourceImage, flipType));
        }
示例#5
0
        private Bitmap CreateNegative(Image sourceImage)
        {
            Bitmap      clone        = ImageOperator.Clone(sourceImage) as Bitmap;
            ColorMatrix invertMatrix = new ColorMatrix(new float[][] {
                new float[] { -1, 0, 0, 0, 0 },
                new float[] { 0, -1, 0, 0, 0 },
                new float[] { 0, 0, -1, 0, 0 },
                new float[] { 0, 0, 0, 1, 0 },
                new float[] { 1, 1, 1, 1, 1 }
            });

            ImageOperator.ApplyColorMatrix(clone, invertMatrix);
            return(clone);
        }
示例#6
0
        /// <summary>
        /// Save the region of a surface to a stream
        /// </summary>
        /// <param name="surface"></param>
        /// <param name="region"></param>
        /// <param name="stream"></param>
        /// <param name="outputSettings"></param>
        /// <returns></returns>
        public static bool SaveToStream(ISurface surface, Region region,
                                        Stream stream, OutputSettings outputSettings)
        {
            Image imageToSave  = null;
            bool  disposeImage = CreateImageFromSurface(surface, outputSettings, out imageToSave);
            bool  ret          = SaveToStream(ImageOperator.CloneArea(imageToSave, region), stream, outputSettings);

            if (disposeImage && imageToSave != null)
            {
                // cleanup if needed
                imageToSave.Dispose();
            }
            return(ret);
        }
示例#7
0
        public Image Apply(Image sourceImage, out Point offsetChange)
        {
            offsetChange = Point.Empty;
            RotateFlipType flipType;

            if (Angle == 90)
            {
                flipType = RotateFlipType.Rotate90FlipNone;
            }
            else if (Angle == -90 || Angle == 270)
            {
                flipType = RotateFlipType.Rotate270FlipNone;
            }
            else
            {
                throw new NotSupportedException("Currently only an angle of 90 or -90 (270) is supported.");
            }
            return(ImageOperator.RotateFlip(sourceImage, flipType));
        }
示例#8
0
        public static IFastBitmap CreateCloneOf(Image source, PixelFormat pixelFormat, Rectangle area)
        {
            Bitmap destination = ImageOperator.CloneArea(source, area, pixelFormat);

            if (destination != null)
            {
                try {
                    FastBitmap fastBitmap = Create(destination) as FastBitmap;
                    fastBitmap.NeedsDispose = true;
                    fastBitmap.Left         = area.Left;
                    fastBitmap.Top          = area.Top;
                    return(fastBitmap);
                }
                catch (Exception ex) {
                    log.Error("Failed to create FastBitmap, " + ex.Message);
                }
            }
            return(null);
        }
示例#9
0
        private static bool SaveJpeg(Image imageToSave, ImageFormat imageFormat, int jpegQuality, Stream stream)
        {
            bool foundEncoder = false;

            foreach (ImageCodecInfo imageCodec in ImageCodecInfo.GetImageEncoders())
            {
                if (imageCodec.FormatID != imageFormat.Guid)
                {
                    continue;
                }

                foundEncoder = true;
                try {
                    EncoderParameters parameters = new EncoderParameters(1);
                    parameters.Param[0] = new EncoderParameter(Encoder.Quality, jpegQuality);
                    // Removing transparency if it's not supported in the output
                    if (Image.IsAlphaPixelFormat(imageToSave.PixelFormat))
                    {
                        Image nonAlphaImage = ImageOperator.Clone(imageToSave, PixelFormat.Format24bppRgb);
                        nonAlphaImage.Save(stream, imageCodec, parameters);
                        nonAlphaImage.Dispose();
                        nonAlphaImage = null;
                    }
                    else
                    {
                        imageToSave.Save(stream, imageCodec, parameters);
                    }
                    return(true);
                }
                catch (Exception ex) {
                    log.Error("Failed to save jpeg, " + ex.Message);
                }
            }

            if (!foundEncoder)
            {
                log.Error("No JPG encoder found.");
            }
            return(false);
        }
示例#10
0
        private static bool CreateImageFromSurface(ISurface surface, OutputSettings outputSettings,
                                                   out Image imageToSave)
        {
            try {
                imageToSave = surface.GetImageForExport();
            }
            catch (Exception ex) {
                imageToSave = null;
                log.Error("Failed to GetImageForExport of surface, " + ex.Message);
            }

            if (imageToSave == null)
            {
                return(false);
            }

            if (outputSettings.Effects != null && outputSettings.Effects.Count > 0)
            {
                // apply effects, if there are any
                Image tmpImage;
                Point ignoreOffset;
                try {
                    tmpImage = ImageOperator.ApplyEffects((Bitmap)imageToSave,
                                                          outputSettings.Effects, out ignoreOffset);
                }
                catch (Exception ex) {
                    tmpImage = null;
                    log.Error("Failed to apply output effect, " + ex.Message);
                }

                if (tmpImage != null)
                {
                    imageToSave.Dispose();
                    imageToSave = tmpImage;
                }
            }

            return(true);
        }
示例#11
0
        // 转换为灰度图像
        private Bitmap CreateGrayscale(Bitmap originalBitmap)
        {
            Bitmap newBitmap = new Bitmap(originalBitmap.Width, originalBitmap.Height);

            using (Graphics g = Graphics.FromImage(newBitmap)) {
                //create the grayscale ColorMatrix
                ColorMatrix colorMatrix = new ColorMatrix(
                    new float[][]
                {
                    new float[] { .3f, .3f, .3f, 0, 0 },
                    new float[] { .59f, .59f, .59f, 0, 0 },
                    new float[] { .11f, .11f, .11f, 0, 0 },
                    new float[] { 0, 0, 0, 1, 0 },
                    new float[] { 0, 0, 0, 0, 1 }
                });

                //create some image attributes
                ImageAttributes attributes = new ImageAttributes();
                attributes.SetColorMatrix(colorMatrix);
                Rectangle rect = new Rectangle(0, 0, originalBitmap.Width, originalBitmap.Height);
                ImageOperator.ApplyImageAttributes(originalBitmap, rect, newBitmap, rect, attributes);
            }
            return(newBitmap);
        }
示例#12
0
 public Image Apply(Image sourceImage, out Point offsetChange)
 {
     offsetChange = Point.Empty;
     return(ImageOperator.ResizeImage(sourceImage, MaintainAspectRatio, false,
                                      Color.Empty, Width, Height, out offsetChange));
 }
示例#13
0
        public Image Sharpen(Image sourceImage, float depth)
        {
            Bitmap sourceBitmap = sourceImage.Clone() as Bitmap;

            if (sourceBitmap == null)
            {
                return(null);
            }

            Bitmap newImage = ImageOperator.CreateEmptyBitmap(sourceBitmap.Width, sourceBitmap.Height, sourceBitmap.PixelFormat,
                                                              Color.Empty, sourceBitmap.HorizontalResolution, sourceBitmap.VerticalResolution);

            Rectangle  rect       = new Rectangle(0, 0, sourceBitmap.Width, sourceBitmap.Height);
            BitmapData bitmapdata = sourceBitmap.LockBits(rect, ImageLockMode.ReadWrite, sourceBitmap.PixelFormat);

            int bytePerPixelColor = GetBytePerPixelColoer(bitmapdata.PixelFormat);

            if (bytePerPixelColor != 3 && bytePerPixelColor != 4)
            {
                log.Error("Pixel format not supported for sharpen:" + bitmapdata.PixelFormat.ToString());
                return(sourceImage);
            }

            //获取像素地址值
            IntPtr ptr = bitmapdata.Scan0;
            //每个图片需要记录长乘以宽*3(RGB,实际顺序应该是BGR)
            int bytes = sourceBitmap.Width * sourceBitmap.Height * bytePerPixelColor;

            byte[] rgbvalues = new byte[bytes];

            System.Runtime.InteropServices.Marshal.Copy(ptr, rgbvalues, 0, bytes);//Marshal使用
            for (int i = 0; i < sourceBitmap.Width; i++)
            {
                for (int j = 0; j < sourceBitmap.Height; j++)
                {
                    int ltIndex  = ((i == 0 ? i : i - 1) + (j == 0 ? j : j - 1) * sourceBitmap.Width) * bytePerPixelColor;
                    int curIndex = (i + j * sourceBitmap.Width) * bytePerPixelColor;

                    int blueValueLT = rgbvalues[ltIndex];
                    int blueValue   = rgbvalues[curIndex];
                    int newValue    = (int)(blueValue + depth * (blueValue - blueValueLT));
                    if (newValue < 0)
                    {
                        newValue = 0;
                    }
                    if (newValue > 255)
                    {
                        newValue = 255;
                    }
                    rgbvalues[curIndex] = (byte)newValue;

                    int greenValueLT = rgbvalues[ltIndex + 1];
                    int greenValue   = rgbvalues[curIndex + 1];
                    newValue = (int)(greenValue + depth * (greenValue - greenValueLT));
                    if (newValue < 0)
                    {
                        newValue = 0;
                    }
                    if (newValue > 255)
                    {
                        newValue = 255;
                    }
                    rgbvalues[curIndex + 1] = (byte)newValue;

                    int redValueLT = rgbvalues[ltIndex + 2];
                    int redValue   = rgbvalues[curIndex + 2];
                    newValue = (int)(redValue + depth * (redValue - redValueLT));
                    if (newValue < 0)
                    {
                        newValue = 0;
                    }
                    if (newValue > 255)
                    {
                        newValue = 255;
                    }
                    rgbvalues[curIndex + 2] = (byte)newValue;
                }
            }
            sourceBitmap.UnlockBits(bitmapdata);

            BitmapData newBitmapdata = newImage.LockBits(rect, ImageLockMode.ReadWrite, sourceBitmap.PixelFormat);

            System.Runtime.InteropServices.Marshal.Copy(rgbvalues, 0, newBitmapdata.Scan0, bytes);//Marshal
            newImage.UnlockBits(newBitmapdata);

            return(newImage);
        }
示例#14
0
        // 由指定bitmap创建一个新有带阴影的bitmap
        protected Bitmap CreateShadow(Image sourceBitmap, float darkness, int shadowSize, Point shadowOffset,
                                      out Point offset, PixelFormat targetPixelformat)
        {
            // Create a new "clean" image
            offset    = shadowOffset;
            offset.X += shadowSize - 1;
            offset.Y += shadowSize - 1;
            Bitmap returnImage = ImageOperator.CreateEmptyBitmap(sourceBitmap.Width + (shadowSize * 2), sourceBitmap.Height + (shadowSize * 2),
                                                                 targetPixelformat, Color.Empty, sourceBitmap.HorizontalResolution, sourceBitmap.VerticalResolution);

            // Make sure the shadow is odd, there is no reason for an even blur!
            if ((shadowSize & 1) == 0)
            {
                shadowSize++;
            }
            bool useGDIBlur = GDIplus.IsBlurPossible(shadowSize);
            // Create "mask" for the shadow
            ColorMatrix maskMatrix = new ColorMatrix();

            maskMatrix.Matrix00 = 0;
            maskMatrix.Matrix11 = 0;
            maskMatrix.Matrix22 = 0;
            if (useGDIBlur)
            {
                maskMatrix.Matrix33 = darkness + 0.1f;
            }
            else
            {
                maskMatrix.Matrix33 = darkness;
            }
            Rectangle shadowRectangle = new Rectangle(new Point(shadowSize, shadowSize), sourceBitmap.Size);

            ImageOperator.ApplyColorMatrix((Bitmap)sourceBitmap, Rectangle.Empty, returnImage, shadowRectangle, maskMatrix);

            // blur "shadow", apply to whole new image
            if (useGDIBlur)
            {
                // Use GDI Blur
                Rectangle newImageRectangle = new Rectangle(0, 0, returnImage.Width, returnImage.Height);
                if (!GDIplus.ApplyBlur(returnImage, newImageRectangle, shadowSize + 1, false))
                {
                    log.Error("Failed to ApplyBlur in GDIplus.");
                }
            }
            else
            {
                // try normal software blur
                ApplyBoxBlur(returnImage, shadowSize);
            }

            // Draw the original image over the shadow
            using (Graphics graphics = Graphics.FromImage(returnImage)) {
                // Make sure we draw with the best quality!
                graphics.SmoothingMode      = SmoothingMode.HighQuality;
                graphics.PixelOffsetMode    = PixelOffsetMode.HighQuality;
                graphics.CompositingQuality = CompositingQuality.HighQuality;
                graphics.InterpolationMode  = InterpolationMode.HighQualityBicubic;
                // draw original with a TextureBrush so we have nice antialiasing!
                using (Brush textureBrush = new TextureBrush(sourceBitmap, WrapMode.Clamp)) {
                    // We need to do a translate-tranform otherwise the image is wrapped
                    graphics.TranslateTransform(offset.X, offset.Y);
                    graphics.FillRectangle(textureBrush, 0, 0, sourceBitmap.Width, sourceBitmap.Height);
                }
            }
            return(returnImage);
        }
示例#15
0
 public Image Apply(Image sourceImage, out Point offsetChange)
 {
     // Make sure the elements move according to the offset the effect made the bitmap move
     offsetChange = new Point(Left, Top);
     return(ImageOperator.ResizeCanvas(sourceImage, BackgroundColor, Left, Right, Top, Bottom));
 }
示例#16
0
        private Image CreateTornEdge(Image sourceImage, int toothHeight, int horizontalToothRange, int verticalToothRange)
        {
            Image returnImage = ImageOperator.CreateEmptyBitmap(sourceImage.Width, sourceImage.Height, PixelFormat.Format32bppArgb, Color.Empty, sourceImage.HorizontalResolution, sourceImage.VerticalResolution);

            using (GraphicsPath path = new GraphicsPath()) {
                Random random            = new Random();
                int    HorizontalRegions = (int)(sourceImage.Width / horizontalToothRange);
                int    VerticalRegions   = (int)(sourceImage.Height / verticalToothRange);

                // Start
                Point previousEndingPoint = new Point(horizontalToothRange, random.Next(1, toothHeight));
                Point newEndingPoint;
                // Top
                for (int i = 0; i < HorizontalRegions; i++)
                {
                    int x = (int)previousEndingPoint.X + horizontalToothRange;
                    int y = random.Next(1, toothHeight);
                    newEndingPoint = new Point(x, y);
                    path.AddLine(previousEndingPoint, newEndingPoint);
                    previousEndingPoint = newEndingPoint;
                }

                // Right
                for (int i = 0; i < VerticalRegions; i++)
                {
                    int x = sourceImage.Width - random.Next(1, toothHeight);
                    int y = (int)previousEndingPoint.Y + verticalToothRange;
                    newEndingPoint = new Point(x, y);
                    path.AddLine(previousEndingPoint, newEndingPoint);
                    previousEndingPoint = newEndingPoint;
                }

                // Bottom
                for (int i = 0; i < HorizontalRegions; i++)
                {
                    int x = (int)previousEndingPoint.X - horizontalToothRange;
                    int y = sourceImage.Height - random.Next(1, toothHeight);
                    newEndingPoint = new Point(x, y);
                    path.AddLine(previousEndingPoint, newEndingPoint);
                    previousEndingPoint = newEndingPoint;
                }

                // Left
                for (int i = 0; i < VerticalRegions; i++)
                {
                    int x = random.Next(1, toothHeight);
                    int y = (int)previousEndingPoint.Y - verticalToothRange;
                    newEndingPoint = new Point(x, y);
                    path.AddLine(previousEndingPoint, newEndingPoint);
                    previousEndingPoint = newEndingPoint;
                }
                path.CloseFigure();

                // Draw the created figure with the original image by using a TextureBrush so we have anti-aliasing
                using (Graphics graphics = Graphics.FromImage(returnImage)) {
                    graphics.SmoothingMode      = SmoothingMode.HighQuality;
                    graphics.PixelOffsetMode    = PixelOffsetMode.HighQuality;
                    graphics.CompositingQuality = CompositingQuality.HighQuality;
                    graphics.InterpolationMode  = InterpolationMode.HighQualityBicubic;
                    using (Brush brush = new TextureBrush(sourceImage)) {
                        // Imporant note: If the target wouldn't be at 0,0 we need to translate-transform!!
                        graphics.FillPath(brush, path);
                    }
                }
            }
            return(returnImage);
        }