public static System.Drawing.Bitmap setPixelFormat2(BitmapSource bitmapsource, System.Drawing.Imaging.PixelFormat format) { //convert image format var src = new System.Windows.Media.Imaging.FormatConvertedBitmap(); src.BeginInit(); src.Source = bitmapsource; if (format == System.Drawing.Imaging.PixelFormat.Format1bppIndexed) { src.DestinationFormat = System.Windows.Media.PixelFormats.BlackWhite; } if (format == System.Drawing.Imaging.PixelFormat.Format8bppIndexed) { src.DestinationFormat = System.Windows.Media.PixelFormats.Gray8; } if (format == System.Drawing.Imaging.PixelFormat.Format24bppRgb) { src.DestinationFormat = System.Windows.Media.PixelFormats.Bgr24; } if (format == System.Drawing.Imaging.PixelFormat.Format32bppRgb) { src.DestinationFormat = System.Windows.Media.PixelFormats.Bgr32; } src.EndInit(); //copy to bitmap Bitmap bitmap = new Bitmap(src.PixelWidth, src.PixelHeight, format); var data = bitmap.LockBits(new Rectangle(Point.Empty, bitmap.Size), System.Drawing.Imaging.ImageLockMode.WriteOnly, format); src.CopyPixels(System.Windows.Int32Rect.Empty, data.Scan0, data.Height * data.Stride, data.Stride); bitmap.UnlockBits(data); return bitmap; }
public MyImageReader(string fileName) { var filePath = Path.Combine(Environment.CurrentDirectory, fileName); _bitmap = new FormatConvertedBitmap(new BitmapImage(new Uri("file://" + filePath)), System.Windows.Media.PixelFormats.Bgr32, null, 0); _pixels = new uint[_bitmap.PixelHeight * _bitmap.PixelWidth]; _bitmap.CopyPixels(_pixels, sizeof(uint) * _bitmap.PixelWidth, 0); }
public static System.Drawing.Bitmap setPixelFormat2(BitmapSource bitmapsource, System.Drawing.Imaging.PixelFormat format) { //convert image format var src = new System.Windows.Media.Imaging.FormatConvertedBitmap(); src.BeginInit(); src.Source = bitmapsource; if (format == System.Drawing.Imaging.PixelFormat.Format1bppIndexed) { src.DestinationFormat = System.Windows.Media.PixelFormats.BlackWhite; } if (format == System.Drawing.Imaging.PixelFormat.Format8bppIndexed) { src.DestinationFormat = System.Windows.Media.PixelFormats.Gray8; } if (format == System.Drawing.Imaging.PixelFormat.Format24bppRgb) { src.DestinationFormat = System.Windows.Media.PixelFormats.Bgr24; } if (format == System.Drawing.Imaging.PixelFormat.Format32bppRgb) { src.DestinationFormat = System.Windows.Media.PixelFormats.Bgr32; } src.EndInit(); //copy to bitmap Bitmap bitmap = new Bitmap(src.PixelWidth, src.PixelHeight, format); var data = bitmap.LockBits(new Rectangle(Point.Empty, bitmap.Size), System.Drawing.Imaging.ImageLockMode.WriteOnly, format); src.CopyPixels(System.Windows.Int32Rect.Empty, data.Scan0, data.Height * data.Stride, data.Stride); bitmap.UnlockBits(data); return(bitmap); }
public static bool[,] Rasterize(Point[] points, int width, int height) { Contract.Requires(points != null); Contract.Requires(width > 0); Contract.Requires(height > 0); Contract.Requires(width % 8 == 0); Contract.Ensures(Contract.Result<bool[,]>() != null); Contract.Ensures(Contract.Result<bool[,]>().GetLength(0) == width); Contract.Ensures(Contract.Result<bool[,]>().GetLength(1) == height); var canvas = new Canvas { Background = Brushes.White, Width = width, Height = height }; var polygon = new Polygon { Stroke = Brushes.Black, Fill = Brushes.Black, StrokeThickness = 1, Points = new PointCollection(points) }; canvas.Children.Add(polygon); RenderOptions.SetEdgeMode(canvas, EdgeMode.Aliased); canvas.Measure(new Size(width, height)); canvas.Arrange(new Rect(0, 0, canvas.DesiredSize.Width, canvas.DesiredSize.Height)); var rtb = new RenderTargetBitmap(width, height, 96, 96, PixelFormats.Default); rtb.Render(canvas); var fmb = new FormatConvertedBitmap(rtb, PixelFormats.BlackWhite, null, 0); var pixels = new byte[width * height / 8]; fmb.CopyPixels(pixels, width / 8, 0); System.Collections.BitArray ba = new System.Collections.BitArray(pixels); var result = new bool[width, height]; for (int i = 0, y = 0; y < height; ++y) for (int x = 0; x < width; ++x, ++i) result[x, y] = !ba[i]; return result; }
public void RGB565LuminanceSource_Should_Give_The_Same_Result_As_RGBLuminanceSource_For_BGR565() { BitmapSource bitmapImage = new BitmapImage(new Uri(samplePicRelPath, UriKind.RelativeOrAbsolute)); bitmapImage = new FormatConvertedBitmap(bitmapImage, PixelFormats.Bgr565, null, 0); var bytes = new byte[bitmapImage.PixelHeight*bitmapImage.PixelWidth*2]; bitmapImage.CopyPixels(bytes, bitmapImage.PixelWidth * 2, 0); var rgb565LuminanceSource = new RGB565LuminanceSource(bytes, bitmapImage.PixelWidth, bitmapImage.PixelHeight); var rgbLuminanceSource = new BitmapSourceLuminanceSource(bitmapImage); Assert.AreEqual(rgbLuminanceSource.ToString(), rgb565LuminanceSource.ToString()); }
public static System.Drawing.Bitmap BmpSource2Img(BitmapSource bmpsource) { //convert image format var src = new System.Windows.Media.Imaging.FormatConvertedBitmap(); src.BeginInit(); src.Source = bmpsource; src.EndInit(); //copy to bitmap Bitmap bitmap = new Bitmap(src.PixelWidth, src.PixelHeight, System.Drawing.Imaging.PixelFormat.DontCare); var data = bitmap.LockBits(new Rectangle(Point.Empty, bitmap.Size), System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.DontCare); src.CopyPixels(System.Windows.Int32Rect.Empty, data.Scan0, data.Height * data.Stride, data.Stride); bitmap.UnlockBits(data); return bitmap; }
/// <summary> /// Extension method /// </summary> /// <param name="bitmapsource"></param> /// <returns></returns> public static Bitmap BitmapSourceToBitmap(this BitmapSource bitmapsource) { //convert image format FormatConvertedBitmap src = new FormatConvertedBitmap(); src.BeginInit(); src.Source = bitmapsource; src.DestinationFormat = System.Windows.Media.PixelFormats.Bgra32; src.EndInit(); //copy to bitmap Bitmap bitmap = new Bitmap(src.PixelWidth, src.PixelHeight, PixelFormat.Format32bppArgb); BitmapData data = bitmap.LockBits(new Rectangle(System.Drawing.Point.Empty, bitmap.Size), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb); src.CopyPixels(Int32Rect.Empty, data.Scan0, data.Height*data.Stride, data.Stride); bitmap.UnlockBits(data); return bitmap; }
public static System.Drawing.Bitmap BmpSource2Img(BitmapSource bmpsource) { //convert image format var src = new System.Windows.Media.Imaging.FormatConvertedBitmap(); src.BeginInit(); src.Source = bmpsource; src.EndInit(); //copy to bitmap Bitmap bitmap = new Bitmap(src.PixelWidth, src.PixelHeight, System.Drawing.Imaging.PixelFormat.DontCare); var data = bitmap.LockBits(new Rectangle(Point.Empty, bitmap.Size), System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.DontCare); src.CopyPixels(System.Windows.Int32Rect.Empty, data.Scan0, data.Height * data.Stride, data.Stride); bitmap.UnlockBits(data); return(bitmap); }
public static byte[,] GetPixels(BitmapSource bitmap) { FormatConvertedBitmap converted = new FormatConvertedBitmap(bitmap, PixelFormats.Gray8, null, 0.5); int width = (int)converted.PixelWidth; int height = (int)converted.PixelHeight; byte[] flat = new byte[width * height]; converted.CopyPixels(flat, width, 0); byte[,] pixels = new byte[height, width]; for (int y = 0; y < height; ++y) for (int x = 0; x < width; ++x) pixels[y, x] = flat[(height - y - 1) * width + x]; return pixels; }
public Bitmap BitmapFromSource(System.Windows.Media.Imaging.BitmapSource bitmapsource) { //convert image format var src = new System.Windows.Media.Imaging.FormatConvertedBitmap(); src.BeginInit(); src.Source = bitmapsource; src.DestinationFormat = System.Windows.Media.PixelFormats.Bgra32; src.EndInit(); //copy to bitmap Bitmap bitmap = new Bitmap(src.PixelWidth, src.PixelHeight, System.Drawing.Imaging.PixelFormat.Format32bppArgb); var data = bitmap.LockBits(new Rectangle(System.Drawing.Point.Empty, bitmap.Size), System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb); src.CopyPixels(System.Windows.Int32Rect.Empty, data.Scan0, data.Height * data.Stride, data.Stride); bitmap.UnlockBits(data); return(bitmap); }
public static Texture2D CreateTextureFromStream(Device device, Stream stream) { var bitmapFrame = BitmapFrame.Create(stream); var bitmap = new FormatConvertedBitmap(bitmapFrame, PixelFormats.Bgra32, null, 0.0); var pixelData = new byte[bitmap.PixelWidth * bitmap.PixelHeight * bitmap.Format.BitsPerPixel / 8]; bitmap.CopyPixels(pixelData, bitmap.PixelWidth * bitmap.Format.BitsPerPixel / 8, 0); var colors = new Color4[bitmap.PixelWidth * bitmap.PixelHeight]; for (int i = 0; i < colors.Length; i++) { var b = pixelData[(i * 4) + 0]; var g = pixelData[(i * 4) + 1]; var r = pixelData[(i * 4) + 2]; var a = pixelData[(i * 4) + 3]; colors[i] = new Color4(r / 255.0f, g / 255.0f, b / 255.0f, a / 255.0f); } return Texture2D.FromColors(device, colors, bitmap.PixelWidth, bitmap.PixelHeight); }
protected override HitTestResult HitTestCore(PointHitTestParameters hitTestParameters) { var source = new FormatConvertedBitmap((BitmapSource) Source, PixelFormats.Bgra32, null, 0); // Get the pixel of the source that was hit var x = (int)(hitTestParameters.HitPoint.X / ActualWidth * source.PixelWidth); var y = (int)(hitTestParameters.HitPoint.Y / ActualHeight * source.PixelHeight); if (x == source.PixelWidth) x--; if (y == source.PixelHeight) y--; var pixelxy = new Int32Rect(x, y, 1, 1); var pixelbgra = new byte[4]; source.CopyPixels(pixelxy, pixelbgra, source.PixelWidth * 4, 0); if (pixelbgra[3] < 5) return null; return new PointHitTestResult(this, hitTestParameters.HitPoint); }
public static Stream ResizeImage(byte[] image, int size) { using (var imageStream = new MemoryStream(image)) { var bitmap = BitmapDecoder.Create(imageStream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.None).Frames[0]; int width = bitmap.Width > bitmap.Height ? size : (int)(bitmap.Width * size / bitmap.Height); int height = bitmap.Width > bitmap.Height ? (int)(bitmap.Height * size / bitmap.Width) : size; var transformedBitmap = new TransformedBitmap(bitmap, new ScaleTransform(width / bitmap.Width, height / bitmap.Height, 0, 0)); var resizedBitmap = BitmapFrame.Create(transformedBitmap); var convertedBitmap = new FormatConvertedBitmap(resizedBitmap, PixelFormats.Bgra32, null, 0); int stride = convertedBitmap.PixelWidth * (convertedBitmap.Format.BitsPerPixel / 8); byte[] data = new byte[stride * convertedBitmap.PixelHeight]; convertedBitmap.CopyPixels(data, stride, 0); var writeBitmap = new WriteableBitmap(size, size, convertedBitmap.DpiX, convertedBitmap.DpiY, PixelFormats.Bgra32, null); writeBitmap.WritePixels(new Int32Rect(0, 0, convertedBitmap.PixelWidth, convertedBitmap.PixelHeight), data, stride, 0); MemoryStream resizeStream = new MemoryStream(); PngBitmapEncoder decoder = new PngBitmapEncoder(); decoder.Frames.Add(BitmapFrame.Create(writeBitmap)); decoder.Save(resizeStream); resizeStream.Position = 0; return resizeStream; } }
public void GetLongitudinalSectionProfile(string FileNameCurve, List<double> list, double hInOnePoint) { BitmapImage myBitmapImage = GetImage(FileNameCurve); if (myBitmapImage == null) { return; } FormatConvertedBitmap newFormatedBitmapSource = new FormatConvertedBitmap(); newFormatedBitmapSource.BeginInit(); newFormatedBitmapSource.Source = myBitmapImage; newFormatedBitmapSource.DestinationFormat = PixelFormats.Rgb24; newFormatedBitmapSource.EndInit(); int width = newFormatedBitmapSource.PixelWidth; int height = newFormatedBitmapSource.PixelHeight; int stride = width * 3; int size = newFormatedBitmapSource.PixelHeight * stride; byte[] pixels = new byte[size]; Array.Clear(pixels, 0, size); newFormatedBitmapSource.CopyPixels(pixels, stride, 0); int x = 0; int y = 0; for (x = 0; x < width; x++) { for (y = 0; y < height; y++) { int index = y * stride + 3 * x; byte red = pixels[index]; byte green = pixels[index + 1]; byte blue = pixels[index + 2]; Color cur_col = Color.FromRgb(red, green, blue); if (cur_col != Color.FromRgb(255, 255, 255)) { list.Add(height - y); break; } } } //double base_point = 0; //if (list.Count > 0) //{ // base_point = list[0]; // if (MathHelper.IsZero(base_point)) // { // base_point = MathHelper.Epsilon; // } //} for (x = 0; x < list.Count; x++) { double cur_point = list[x]; double factor = cur_point * hInOnePoint; list[x] = factor; } }
public void GetCrossSectionProfile(List<Point> list, string fileName, int TotalPoints, double fPointWidth) { BitmapImage myBitmapImage = GetImage(fileName); if (myBitmapImage == null) { return; } FormatConvertedBitmap newFormatedBitmapSource = new FormatConvertedBitmap(); newFormatedBitmapSource.BeginInit(); newFormatedBitmapSource.Source = myBitmapImage; newFormatedBitmapSource.DestinationFormat = PixelFormats.Rgb24; newFormatedBitmapSource.EndInit(); int width = newFormatedBitmapSource.PixelWidth; int stride = width * 3; int size = newFormatedBitmapSource.PixelHeight * stride; byte[] pixels = new byte[size]; Array.Clear(pixels, 0, size); newFormatedBitmapSource.CopyPixels(pixels, stride, 0); int x = 0; int y = 0; Point ptCenter = new Point(); ptCenter.X = newFormatedBitmapSource.PixelWidth / 2; ptCenter.Y = newFormatedBitmapSource.PixelHeight / 2; int r_begin_min = (int)Math.Min(ptCenter.X, ptCenter.Y); ScaleTransform scaleTransform = new ScaleTransform(fPointWidth, fPointWidth); double delta = TotalPoints / 360; for (double angle = 0; angle < 360; angle += delta) { double rad_angle = Math.PI * angle / 180.0; int r_begin = (int)Math.Sqrt(2 * r_begin_min * r_begin_min); for (double r = r_begin; r > 0; r-=1) { x = (int)(r * Math.Cos(rad_angle)) + (int)ptCenter.X; y = (int)(r * Math.Sin(rad_angle)) + (int)ptCenter.Y; if (x >= newFormatedBitmapSource.PixelWidth || y >= newFormatedBitmapSource.PixelHeight || x < 0 || y < 0) { continue; } int index = y * stride + 3 * x; byte red = pixels[index]; byte green = pixels[index + 1]; byte blue = pixels[index + 2]; Color cur_col = Color.FromRgb(red, green, blue); if (cur_col != Color.FromRgb(255, 255, 255)) { int x_add = x - (int)ptCenter.X; int y_add = y - (int)ptCenter.Y; Point ptToAdd = new Point(x_add, y_add); if (list.Count == 0 || list.Last() != ptToAdd) { list.Add(ptToAdd); if (list.Count == 215) { int h = 0 + 4; } } break; } } } if (scaleTransform != null) { for (int i = 0; i < list.Count; i++) { list[i] = scaleTransform.Transform(list[i]); } } }
private void load_Click(object sender, RoutedEventArgs e) { OpenFileDialog open_dialog = new OpenFileDialog(); Nullable<bool> result = open_dialog.ShowDialog(); if (result == true) { try { BitmapImage myBitmapImage = new BitmapImage(new Uri(open_dialog.FileName, UriKind.Absolute)); Molusk_image.Visibility = System.Windows.Visibility.Visible; //convert to grayscale FormatConvertedBitmap newFormatedBitmapSource = new FormatConvertedBitmap(); newFormatedBitmapSource.BeginInit(); newFormatedBitmapSource.Source = myBitmapImage; newFormatedBitmapSource.DestinationFormat = PixelFormats.Gray8; newFormatedBitmapSource.EndInit(); double dpi = 96; int width = newFormatedBitmapSource.PixelWidth; int height = newFormatedBitmapSource.PixelHeight; int stride = width; // 4 bytes per pixel byte[] pixelData = new byte[stride * height]; newFormatedBitmapSource.CopyPixels(pixelData, stride, 0); BitmapSource bmpSource = BitmapSource.Create(width, height, dpi, dpi, PixelFormats.Gray8, null, pixelData, stride); Molusk_image.Source = bmpSource; Molusk_image.RenderTransform = trGrp; } catch { MessageBox.Show("произошла ошибка! Это не изображение! Попробуйте снова."); } } }
/// <summary> /// 从图片中获取背景颜色 /// </summary> /// <param name="bitmap">图片</param> public static Color GetImageColorForBackground(FormatConvertedBitmap bitmap) { const int bytesPerPixel = 3; if (bitmap.CanFreeze) bitmap.Freeze(); var pixels = new byte[bitmap.PixelHeight * bitmap.PixelWidth * bytesPerPixel]; bitmap.CopyPixels(pixels, bitmap.PixelWidth * bytesPerPixel, 0); var width = bitmap.PixelWidth; var height = bitmap.PixelHeight; //计算颜色的均值 Color color = GetColorOfRegion(pixels, width, height, 0, width, 0, height); var hsl = new HslColor(color); if (IsNotSaturateEnough(hsl) && !IsAlmostZeroSaturation(hsl)) hsl.Saturation += 0.2; return Revise(hsl).ToRgb(); }
System.Drawing.Bitmap GetBitmap() { BitmapSource contentImage = GetImage(); int imageWidth = (int)contentImage.Width; int imageHeight = (int)contentImage.Height; System.Drawing.Bitmap bitmapFinal = new System.Drawing.Bitmap( imageWidth, imageHeight, System.Drawing.Imaging.PixelFormat.Format32bppRgb); System.Drawing.Imaging.BitmapData bmData = bitmapFinal.LockBits( new System.Drawing.Rectangle(0, 0, imageWidth, imageHeight), System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppRgb); FormatConvertedBitmap formatConverter = new FormatConvertedBitmap(); formatConverter.BeginInit(); formatConverter.Source = contentImage; formatConverter.DestinationFormat = PixelFormats.Bgr32; formatConverter.EndInit(); CodeAccessPermission mediaAccessPermission = SecurityHelper.CreateMediaAccessPermission(null); if (mediaAccessPermission != null) { mediaAccessPermission.Assert(); //BlessedAssert } try { formatConverter.CopyPixels( new Int32Rect(0, 0, imageWidth, imageHeight), bmData.Scan0, bmData.Stride * (bmData.Height - 1) + (bmData.Width * 4), bmData.Stride); } finally { if (mediaAccessPermission != null) { CodeAccessPermission.RevertAssert(); } } bitmapFinal.UnlockBits(bmData); return bitmapFinal; }
/// <summary> /// Swap the colors in a bitmap based on a color mapping provided by the ColorCallback</summary> /// <param name="bitmapSource">Original bitmap</param> /// <param name="colorCallback">Callback to provide the color mapping</param> /// <returns>Color-swapped bitmap</returns> public static BitmapSource SwapColors(BitmapSource bitmapSource, ColorCallback colorCallback) { if (colorCallback == null) { throw new ArgumentNullException("colorCallback"); } BitmapSource source = bitmapSource; if (bitmapSource != null) { PixelFormat destinationFormat = PixelFormats.Bgra32; BitmapPalette destinationPalette = null; double alphaThreshold = 0.0; FormatConvertedBitmap bitmap = new FormatConvertedBitmap(bitmapSource, destinationFormat, destinationPalette, alphaThreshold); int pixelWidth = bitmap.PixelWidth; int pixelHeight = bitmap.PixelHeight; int stride = 4 * pixelWidth; byte[] pixels = new byte[stride * pixelHeight]; bitmap.CopyPixels(pixels, stride, 0); for (int i = 0; i < pixels.Length; i += 4) { Color color = Color.FromArgb(pixels[i + 3], pixels[i + 2], pixels[i + 1], pixels[i]); Color color2 = colorCallback(color); if (color2 != color) { pixels[i] = color2.B; pixels[i + 1] = color2.G; pixels[i + 2] = color2.R; pixels[i + 3] = color2.A; } } source = BitmapSource.Create(pixelWidth, pixelHeight, bitmap.DpiX, bitmap.DpiY, destinationFormat, destinationPalette, pixels, stride); source.Freeze(); } return source; }
private static byte[] GetBitmapPixels(BitmapSource renderBitmap, int width, int height) { // The stride is the width of a single row of pixels (a scan line), rounded up to a four-byte boundary. // The stride is always greater than or equal to the actual pixel width. If the stride is positive, // the bitmap is top-down. If the stride is negative, the bitmap is bottom-up. int stride = width * 4; FormatConvertedBitmap bitmap = new FormatConvertedBitmap(); bitmap.BeginInit(); bitmap.DestinationFormat = PixelFormats.Bgra32; bitmap.Source = renderBitmap; bitmap.EndInit(); byte[] pixels = new byte[stride * height]; bitmap.CopyPixels(Int32Rect.Empty, pixels, stride, 0); return pixels; }
public override ImageData Read(Stream stream, ImageMetaData info) { var meta = info as BipMetaData; if (null == meta) throw new ArgumentException ("BipFormat.Read should be supplied with BipMetaData", "info"); var header = new byte[0x7c]; var bitmap = new WriteableBitmap ((int)meta.Width, (int)meta.Height, ImageData.DefaultDpiX, ImageData.DefaultDpiY, PixelFormats.Bgra32, null); foreach (var tile in meta.Tiles) { stream.Position = tile.Offset; if (header.Length != stream.Read (header, 0, header.Length)) throw new InvalidFormatException ("Invalid tile header"); if (!Binary.AsciiEqual (header, "PNGFILE2")) throw new InvalidFormatException ("Unknown tile format"); int data_size = LittleEndian.ToInt32 (header, 0x18) - header.Length; int alpha = LittleEndian.ToInt32 (header, 0x68); int x = LittleEndian.ToInt32 (header, 0x6c); int y = LittleEndian.ToInt32 (header, 0x70); using (var png = new StreamRegion (stream, stream.Position, data_size, true)) { var decoder = new PngBitmapDecoder (png, BitmapCreateOptions.None, BitmapCacheOption.OnLoad); BitmapSource frame = decoder.Frames[0]; PixelFormat format = 0 == alpha ? PixelFormats.Bgr32 : PixelFormats.Bgra32; var converted = new FormatConvertedBitmap (frame, format, null, 0); int stride = converted.PixelWidth * 4; var pixels = new byte[stride * converted.PixelHeight]; converted.CopyPixels (pixels, stride, 0); for (int p = 0; p < pixels.Length; p += 4) { byte r = pixels[p]; pixels[p] = pixels[p+2]; pixels[p+2] = r; int a = 0 == alpha ? 0xff : pixels[p+3] * 0xff / 0x80; if (a > 0xff) a = 0xff; pixels[p+3] = (byte)a; } var rect = new Int32Rect (tile.Left+x, tile.Top+y, converted.PixelWidth, converted.PixelHeight); bitmap.WritePixels (rect, pixels, stride, 0); } } bitmap.Freeze(); return new ImageData (bitmap, meta); }
/// <summary> /// 从图片中获取背景颜色 /// </summary> /// <param name="image">图片</param> /// <param name="callback">计算完成后调用的委托</param> public static void GetImageColorForBackgroundAsync(BitmapSource image, ComputeCompleteCallback callback) { FormatConvertedBitmap bitmap = null; const int bytesPerPixel = 3; byte[] pixels = null; int width = 0; int height = 0; bool isFrozen = image.IsFrozen; if (!isFrozen) { //由于image没有冻结,所以image不能跨线程使用,这时要在当前线程中将image转换为另一个位图 bitmap = new FormatConvertedBitmap(image, PixelFormats.Rgb24, BitmapPalettes.WebPalette, 0); if (bitmap.CanFreeze) bitmap.Freeze(); pixels = new byte[bitmap.PixelHeight * bitmap.PixelWidth * bytesPerPixel]; bitmap.CopyPixels(pixels, bitmap.PixelWidth * bytesPerPixel, 0); width = bitmap.PixelWidth; height = bitmap.PixelHeight; } ThreadPool.QueueUserWorkItem(new WaitCallback((state) => { if (isFrozen) { //由于image已经冻结,所以image可以跨线程使用,这时在新线程中将image转换为另一个位图 bitmap = new FormatConvertedBitmap(image, PixelFormats.Rgb24, BitmapPalettes.WebPalette, 0); if (bitmap.CanFreeze) bitmap.Freeze(); pixels = new byte[bitmap.PixelHeight * bitmap.PixelWidth * bytesPerPixel]; bitmap.CopyPixels(pixels, bitmap.PixelWidth * bytesPerPixel, 0); width = bitmap.PixelWidth; height = bitmap.PixelHeight; } //计算颜色的均值 int sum = width * height; int r = 0, g = 0, b = 0; int offset = 0; for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { r += pixels[offset++]; g += pixels[offset++]; b += pixels[offset++]; } } r = r / sum; g = g / sum; b = b / sum; Color color1 = Color.FromRgb((byte)r, (byte)g, (byte)b); //计算图片右部的颜色均值 r = 0; g = 0; b = 0; int jstart = (int)(width * (1 - RightSideWidth)); sum = (width - jstart) * width; for (int i = 0; i < height; i++) { for (int j = jstart; j < width; j++) { r += pixels[(i * width + j) * bytesPerPixel + 0]; g += pixels[(i * width + j) * bytesPerPixel + 1]; b += pixels[(i * width + j) * bytesPerPixel + 2]; } } r = r / sum; g = g / sum; b = b / sum; Color color2 = Color.FromRgb((byte)r, (byte)g, (byte)b); //根据上面计算出来的两个颜色计算最终颜色 HSLColor hsl1 = new HSLColor(color1); HSLColor hsl2 = new HSLColor(color2); hsl1.Hue += 10; if (IsNotSaturateEnough(hsl1) && !IsAlmostZeroSaturation(hsl1)) hsl1.Saturation += 0.2; callback(Revise(hsl1, hsl2).ToRGB()); })); }
private Document OnLoadImpl(Stream input) { WmpBitmapDecoder wbd = new WmpBitmapDecoder(input, BitmapCreateOptions.None, BitmapCacheOption.None); BitmapFrame frame0 = wbd.Frames[0]; Document output = new Document(frame0.PixelWidth, frame0.PixelHeight); output.DpuUnit = MeasurementUnit.Inch; output.DpuX = frame0.DpiX; output.DpuY = frame0.DpiY; BitmapLayer layer = Layer.CreateBackgroundLayer(output.Width, output.Height); MemoryBlock memoryBlock = layer.Surface.Scan0; IntPtr scan0 = memoryBlock.Pointer; FormatConvertedBitmap fcb = new FormatConvertedBitmap(frame0, System.Windows.Media.PixelFormats.Bgra32, null, 0); fcb.CopyPixels(Int32Rect.Empty, scan0, (int)memoryBlock.Length, layer.Surface.Stride); output.Layers.Add(layer); BitmapMetadata hdMetadata = (BitmapMetadata)frame0.Metadata; CopyMetadataTo(output.Metadata, hdMetadata); // WPF doesn't give us an IDisposable implementation on its types Utility.GCFullCollect(); return output; }