private WriteableBitmap _applyShader(BitmapFrame img, Func <byte, byte, byte, byte, Color> shader) { const double DPI = 96; if (Methods.CanUseIndexed8 || img.Format != PixelFormats.Indexed8) { int width = img.PixelWidth; int height = img.PixelHeight; int stride = (int)Math.Ceiling(width * img.Format.BitsPerPixel / 8f); byte[] pixelData = new byte[stride * height]; img.CopyPixels(pixelData, stride, 0); _darkTheme(pixelData, img.Format, null, shader); var wBitmap = new WriteableBitmap(BitmapSource.Create(width, height, DPI, DPI, img.Format, img.Palette, pixelData, stride)); wBitmap.Freeze(); return(wBitmap); } else { List <Color> colors = new List <Color>(img.Palette.Colors); byte[] pixelData = new byte[img.PixelWidth * img.PixelHeight * img.Format.BitsPerPixel / 8]; img.CopyPixels(pixelData, img.PixelWidth * img.Format.BitsPerPixel / 8, 0); _darkTheme(pixelData, img.Format, colors, shader); var wBitmap = WpfImaging.ToBgra32FromIndexed8(pixelData, colors, img.PixelWidth, img.PixelHeight); wBitmap.Freeze(); return(wBitmap); } }
private static byte[] ApplyColoring(Color templateColor, BitmapFrame frame, int iWidth, int iHeight) { byte[] iPixel = new byte[iWidth * iHeight * 8]; Int32 stride = (frame.PixelWidth * frame.Format.BitsPerPixel + 7) / 8; if (frame.Format == PixelFormats.Rgba64) { // PNG images for my vocabulary.zip file are typically in the RGBA64 format frame.CopyPixels(iPixel, stride, 0); for (int i = 0; i < iPixel.Length; i += 8) { int weightThreshold = 1000; uint pixelContent = (((uint)iPixel[i]) << 8) + iPixel[i + 1] + (((uint)iPixel[i + 2]) << 8) + iPixel[i + 3] + (((uint)iPixel[i + 4]) << 8) + iPixel[i + 5]; if (pixelContent > weightThreshold) { iPixel[i] = (byte)((((UInt16)(templateColor.ScR * 65535)) & 0xFF00) >> 8); iPixel[i + 1] = (byte)((((UInt16)(templateColor.ScR * 65535)) & 0xFF)); iPixel[i + 2] = (byte)((((UInt16)(templateColor.ScG * 65535)) & 0xFF00) >> 8); iPixel[i + 3] = (byte)((((UInt16)(templateColor.ScG * 65535)) & 0xFF)); iPixel[i + 4] = (byte)((((UInt16)(templateColor.ScB * 65535)) & 0xFF00) >> 8); iPixel[i + 5] = (byte)((((UInt16)(templateColor.ScB * 65535)) & 0xFF)); iPixel[i + 6] = (byte)((((UInt16)(templateColor.ScA * 65535)) & 0xFF00) >> 8);; iPixel[i + 7] = (byte)((((UInt16)(templateColor.ScA * 65535)) & 0xFF));; } } } else if (frame.Format == PixelFormats.Pbgra32) { iPixel = new byte[iHeight * stride]; frame.CopyPixels(iPixel, stride, 0); for (int i = 0; i < iPixel.Length; i += 4) { int weightThreshold = 2; // if pixel RGB add up to more than 2 we treat it as a 'black' pixel that can be colorized based on templatecolor uint pixelContent = (uint)iPixel[i] + (uint)iPixel[i + 1] + +(uint)iPixel[i + 2] + +(uint)iPixel[i + 3]; //+ (uint)iPixel[i + 2] + (uint)iPixel[i + 3];//(((uint)iPixel[i]) << 8) + iPixel[i + 1] + (((uint)iPixel[i + 2]) << 8) + iPixel[i + 3] + (((uint)iPixel[i + 4]) << 8) + iPixel[i + 5]; if (pixelContent > weightThreshold) { iPixel[i + 0] = (byte)(templateColor.ScB * 255); iPixel[i + 1] = (byte)(templateColor.ScG * 255); iPixel[i + 2] = (byte)(templateColor.ScR * 255); iPixel[i + 3] = (byte)(templateColor.ScA * 255); } } } else { System.Diagnostics.Debug.WriteLine("Unsupported format applying color to image: " + frame.Format); throw new ArgumentException("Unsupported format applying color to image: " + frame.Format); } return(iPixel); }
private void LoadTifImages(string file) { _fileName = System.IO.Path.GetFileName(file); _frame = BitmapDecoder.Create(new Uri(file), BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad).Frames.First(); int pixelSize = _frame.Format.BitsPerPixel / 8; int stride = _frame.PixelWidth * pixelSize; int size = _frame.PixelHeight * stride; _imagePixels = new byte[size]; _frame.CopyPixels(_imagePixels, stride, 0); _tips.Clear(); _nodes.Clear(); _vVNodes.Clear(); _edges.Clear(); _erosionDilatationValue = 0; tbErosionDilatation.Text = $"{_erosionDilatationValue}"; _openingClosingValue = 0; tbOpeningClosing.Text = $"{_openingClosingValue}"; int NodeCounter = 0; // Take every four pixel of the image for (int x = 0; x < _frame.PixelWidth; x = x + 12) { for (int y = 0; y < _frame.PixelHeight; y = y + 12) { int pixelIndex = y * stride + pixelSize * x; int pixelGrayScale = (int)((_imagePixels[pixelIndex] * .21) + (_imagePixels[pixelIndex + 1] * .71) + (_imagePixels[pixelIndex + 2] * .071)); if (pixelGrayScale <= _grayScaleValue) { _nodes.Add(new Node("", x, y, 1)); _tips.Add($"Node_{NodeCounter}", NodeCounter); NodeCounter++; } else if (pixelGrayScale > _grayScaleValue && pixelGrayScale < 220) { _nodes.Add(new Node("", x, y, 0)); _tips.Add($"Node_{NodeCounter}", NodeCounter); NodeCounter++; } } } _vVNodes = _nodes; _boundingBox = new double[] { -50, -20, _frame.PixelWidth + 50, _frame.PixelHeight + 20 }; Title = $"Pattern Analyser - Voronoi Diagramm ({_fileName}) - Status: wird berechnet..."; Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); _voronoiGraph = Fortune.ComputeVoronoiGraph(_nodes.MapNodeToVector()); _voronoiGraphCopy = _voronoiGraph; stopWatch.Stop(); _edges = _voronoiGraph.Edges.MapEdgeHashSetToEdgeList(ActualHeight, true, _scaled).ToList(); this.MyDotViewer.LoadPlain(_nodes, _edges, _fileName, _boundingBox, _frame, 1); Title = $"Pattern Analyser - Voronoi Diagramm ({_fileName}) - Dauer: {stopWatch.ElapsedMilliseconds.ToString()} ms"; //this.MyDotViewer.LoadSourceImage(_frame, System.IO.Path.GetFileName(file)); }
public static IntPtr GetHIcon(ImageSource source) { BitmapFrame frame = source as BitmapFrame; if (frame != null && frame.Decoder.Frames.Count > 0) { frame = frame.Decoder.Frames[0]; int width = frame.PixelWidth; int height = frame.PixelHeight; int stride = width * ((frame.Format.BitsPerPixel + 7) / 8); byte[] bits = new byte[height * stride]; frame.CopyPixels(bits, stride, 0); // pin the bytes in memory (avoids using unsafe context) GCHandle gcHandle = GCHandle.Alloc(bits, GCHandleType.Pinned); Bitmap bitmap = new Bitmap( width, height, stride, System.Drawing.Imaging.PixelFormat.Format32bppPArgb, gcHandle.AddrOfPinnedObject()); IntPtr hIcon = bitmap.GetHicon(); gcHandle.Free(); return(hIcon); } return(IntPtr.Zero); }
public static ImageSource ColourImage(string resource, SolidColorBrush brush) { // Copy pixel colour values from existing image. // (This loads them from an embedded resource. BitmapDecoder can work with any Stream, though.) //StreamResourceInfo x = Application.GetResourceStream(new Uri(BaseUriHelper.GetBaseUri(this), "Image.png")); var uri = new Uri("pack://application:,,,/LightBlue.MultiHost;component/" + resource); StreamResourceInfo x = Application.GetResourceStream(uri); BitmapDecoder dec = BitmapDecoder.Create(x.Stream, BitmapCreateOptions.None, BitmapCacheOption.Default); BitmapFrame image = dec.Frames[0]; byte[] pixels = new byte[image.PixelWidth * image.PixelHeight * 4]; image.CopyPixels(pixels, image.PixelWidth * 4, 0); // Modify the alpha pixels for (int i = 0; i < pixels.Length / 4; ++i) { byte a = pixels[i * 4 + 3]; if (a != 0) { pixels[i * 4] = brush.Color.B; pixels[i * 4 + 1] = brush.Color.G; pixels[i * 4 + 2] = brush.Color.R; } } // Write the modified pixels into a new bitmap and use that as the source of an Image var bmp = new WriteableBitmap(image.PixelWidth, image.PixelHeight, image.DpiX, image.DpiY, PixelFormats.Pbgra32, null); bmp.WritePixels(new Int32Rect(0, 0, image.PixelWidth, image.PixelHeight), pixels, image.PixelWidth * 4, 0); return(bmp); }
public Bitmap AsGDI(Profile profile = null) { bool pop = false; try { if (gdiBitmap != null) { return(gdiBitmap); } if (profile != null) { profile.Push("SmartBitmap.AsGDI"); pop = true; } if (wpfBitmap != null) { Bitmap gdiBitmap = new Bitmap(wpfBitmap.PixelWidth, wpfBitmap.PixelHeight, System.Drawing.Imaging.PixelFormat.Format32bppRgb); ApplyProperties(); BitmapData d = gdiBitmap.LockBits(new Rectangle(0, 0, gdiBitmap.Width, gdiBitmap.Height), ImageLockMode.WriteOnly, ManagedBitmap32.Format); int * scan0 = (int *)d.Scan0.ToPointer(); int stride = d.Stride; Debug.Assert(stride > 0); wpfBitmap.CopyPixels(new System.Windows.Int32Rect(0, 0, gdiBitmap.Width, gdiBitmap.Height), new IntPtr(scan0), stride, 0 /*offset*/); gdiBitmap.UnlockBits(d); wpfBitmap = null; return(gdiBitmap); } if (managedBitmap != null) { gdiBitmap = managedBitmap.CloneToGDI(); managedBitmap.Dispose(); managedBitmap = null; return(gdiBitmap); } } finally { if ((profile != null) && pop) { profile.Pop(); } } Debug.Assert(false); throw new InvalidOperationException(); }
/// <summary> /// Creates a WinForms <see cref="Bitmap"/> from the <see cref="Image"/>. /// </summary> /// <param name="image">The <see cref="Image"/> to convert into a <see cref="Bitmap"/>.</param> /// <returns>A <see cref="Bitmap"/> that references the data in <see cref="Image"/>.</returns> public static System.Drawing.Image CreateBitmap(this Image image) { if (image is null) { throw new ArgumentNullException(nameof(image)); } System.Drawing.Imaging.PixelFormat pixelFormat; // Take a new reference on the image to ensure that the object // cannot be disposed by another thread while we have a copy of its Buffer using (Image reference = image.DuplicateReference()) { unsafe { switch (reference.Format) { case ImageFormat.ColorBgra32: pixelFormat = System.Drawing.Imaging.PixelFormat.Format32bppArgb; break; case ImageFormat.Depth16: case ImageFormat.IR16: pixelFormat = System.Drawing.Imaging.PixelFormat.Format16bppGrayScale; break; case ImageFormat.ColorMjpg: Byte[] buffer = new byte[image.SizeBytes]; System.Runtime.InteropServices.Marshal.Copy(image.Buffer, buffer, 0, image.SizeBytes); JpegBitmapDecoder decoder = new JpegBitmapDecoder(new MemoryStream(buffer), BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default); BitmapFrame frame = decoder.Frames[0]; Bitmap lbmpBitmap = new Bitmap(frame.PixelWidth, frame.PixelHeight); Rectangle lrRect = new Rectangle(0, 0, lbmpBitmap.Width, lbmpBitmap.Height); BitmapData lbdData = lbmpBitmap.LockBits(lrRect, ImageLockMode.WriteOnly, (frame.Format.BitsPerPixel == 24 ? PixelFormat.Format24bppRgb : PixelFormat.Format32bppArgb)); frame.CopyPixels(System.Windows.Int32Rect.Empty, lbdData.Scan0, lbdData.Height * lbdData.Stride, lbdData.Stride); lbmpBitmap.UnlockBits(lbdData); return(lbmpBitmap); // pixelFormat = System.Drawing.Imaging.PixelFormat.; // MjpegProcessor.MjpegDecoder() //break; default: throw new Exception($"Pixel format {reference.Format} cannot be converted to a BitmapSource"); } using (image) { return(new Bitmap( image.WidthPixels, image.HeightPixels, image.StrideBytes, pixelFormat, image.Buffer)); } } } }
public ManagedBitmap32(BitmapFrame wpfBitmap) : this(wpfBitmap.PixelWidth, wpfBitmap.PixelHeight) { wpfBitmap.CopyPixels( new System.Windows.Int32Rect(0, 0, wpfBitmap.PixelWidth, wpfBitmap.PixelHeight), new IntPtr(this.scan0), TotalBytes, this.stride); }
private void UpdateWritableBitmap(BitmapFrame frame) { Application.Current.Dispatcher.Invoke(() => { writableBitmap.Lock(); frame.CopyPixels(new System.Windows.Int32Rect(0, 0, 3841, 2162), writableBitmap.BackBuffer, (int)writableBitmap.BackBufferStride * (int)writableBitmap.Height, (int)writableBitmap.BackBufferStride); writableBitmap.AddDirtyRect(new System.Windows.Int32Rect(0, 0, 3841, 2162)); writableBitmap.Unlock(); }, System.Windows.Threading.DispatcherPriority.Background); }
public static Bitmap CreateBitmapFromFrame(BitmapFrame frame) { Bitmap bitmap = new Bitmap(frame.PixelWidth, frame.PixelHeight, PixelFormat.Format32bppArgb); BitmapData bitmapData = bitmap.LockBits(new Rectangle(System.Drawing.Point.Empty, bitmap.Size), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb); frame.CopyPixels(Int32Rect.Empty, bitmapData.Scan0, bitmapData.Height * bitmapData.Stride, bitmapData.Stride); bitmap.UnlockBits(bitmapData); return(bitmap); }
private Bitmap JpegToBitmap(Stream jpg) { JpegBitmapDecoder ldDecoder = new JpegBitmapDecoder(jpg, BitmapCreateOptions.None, BitmapCacheOption.None); BitmapFrame lfFrame = ldDecoder.Frames[0]; Bitmap lbmpBitmap = new Bitmap(lfFrame.PixelWidth, lfFrame.PixelHeight); Rectangle lrRect = new Rectangle(0, 0, lbmpBitmap.Width, lbmpBitmap.Height); BitmapData lbdData = lbmpBitmap.LockBits(lrRect, ImageLockMode.WriteOnly, (lfFrame.Format.BitsPerPixel == 24 ? PixelFormat.Format24bppRgb : PixelFormat.Format32bppArgb)); lfFrame.CopyPixels(System.Windows.Int32Rect.Empty, lbdData.Scan0, lbdData.Height * lbdData.Stride, lbdData.Stride); lbmpBitmap.UnlockBits(lbdData); return(lbmpBitmap); }
private static BitmapSource Convert(BitmapFrame frame) { int stride = frame.PixelWidth * (frame.Format.BitsPerPixel / 8); byte[] pixels = new byte[frame.PixelHeight * stride]; frame.CopyPixels(pixels, stride, 0); var bmpSource = BitmapSource.Create(frame.PixelWidth, frame.PixelHeight, frame.DpiX, frame.DpiY, frame.Format, frame.Palette, pixels, stride); return(bmpSource); }
private BitmapImage TiffFrameToBitmapImage(BitmapFrame frame) { int stride = (int)frame.PixelWidth * ((frame.Format.BitsPerPixel + 7) / 8); byte[] pixels = new byte[(int)frame.PixelHeight * stride]; BitmapImage img;; frame.CopyPixels(pixels, stride, 0); img = new BitmapImage(); //img.CopyPixels(pixels, stride, 0); return(img); }
public void Method2() { Array myPixels = (...); while (true) { // Prepare image BitmapFrame bf = BitmapFrame.Create(screen); RenderOptions.SetBitmapScalingMode(bf, BitmapScalingMode.LowQuality); bf.CopyPixels(new Int32Rect(0, 0, width, height), myPixels, width * 4, 0); lock (pixelsLock) { // Copy the hard work to shared storage Array.Copy(sourceArray: myPixels, destinationArray: shared, length: myPixels.GetUpperBound(0) - 1); } } }
public string LoadBitmap(string path) { string text; using (FileStream fs = File.Open(path, FileMode.Open)) { BitmapDecoder decoder = PngBitmapDecoder.Create(fs, BitmapCreateOptions.DelayCreation, BitmapCacheOption.Default); BitmapFrame frame = decoder.Frames[0]; byte[] bytes = new byte[frame.PixelWidth * frame.PixelHeight]; frame.CopyPixels(bytes, frame.PixelWidth, 0); text = Encoding.Unicode.GetString(bytes); } return(text); }
private Array FileConvertArray(string filename, out PixelFormat format) { Array arr; using (FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read)) { BitmapFrame bitmapFrame = BitmapFrame.Create( fs, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default ); int width = bitmapFrame.PixelWidth; int height = bitmapFrame.PixelHeight; format = bitmapFrame.Format; int stride = ((width * format.BitsPerPixel + 31) / 32) * 4; if (format == PixelFormats.Gray16) { arr = new ushort[width * height]; } else if (format == PixelFormats.Rgb48) { arr = new ushort[width * 3 * height]; } else { arr = new byte[stride * height]; } // 輝度データを配列へコピー bitmapFrame.CopyPixels(arr, stride, 0); fs.Dispose(); } GC.Collect(); return(arr); }
private ImageLoaderProxyPixelData GetBitmapImageBytes(string fileName) { // All of the BitmapSource creation occurs in this method, keeping the calls to // MemoryPressure.ProcessAdd() localized to this app domain // Load the image from file BitmapFrame bmpFrame = BitmapFrame.Create(new Uri(fileName)); int stride = bmpFrame.PixelWidth * bmpFrame.Format.BitsPerPixel; byte[] pixels = new byte[bmpFrame.PixelHeight * stride]; // Construct and return the image information bmpFrame.CopyPixels(pixels, stride, 0); return(new ImageLoaderProxyPixelData() { Pixels = pixels, Stride = stride, Rect = new Int32Rect(0, 0, bmpFrame.PixelWidth, bmpFrame.PixelHeight) }); }
private static Dictionary <char, byte[]> GenerateTypeface(Uri bitmapPath, int glyphWidth, int glyphHeight, int rawStride) { Dictionary <char, byte[]> toReturn = new Dictionary <char, byte[]>(); // Assumes bitmap is of proper pixelformat (Indexed1) PngBitmapDecoder b = new PngBitmapDecoder(bitmapPath, BitmapCreateOptions.IgnoreColorProfile, BitmapCacheOption.Default); BitmapFrame sheet = b.Frames[0]; int imageIndex = 0; byte[] rawImage = new byte[rawStride * glyphHeight]; for (int j = 0; j < sheet.PixelHeight; j += glyphHeight) { for (int i = 0; i < sheet.PixelWidth; i += glyphWidth) { sheet.CopyPixels(new Int32Rect(i, j, glyphWidth, glyphHeight), rawImage, rawStride, 0); toReturn[MasterIndexList[imageIndex]] = (byte[])rawImage.Clone(); imageIndex++; } } return(toReturn); }
public static IconHandle Create(ImageSource imageSource) { IconHandle result = IconHandle.Invalid; if (imageSource != null) { // Initialize bitmap rectangle and try to cast image source to bitmap frame Rect bitmapRect = new Rect(new Size(imageSource.Width, imageSource.Height)); BitmapFrame bitmapFrame = imageSource as BitmapFrame; if (bitmapFrame == null || !(bitmapFrame.Decoder is IconBitmapDecoder)) { // Create drawing visual DrawingVisual drawingVisual = new DrawingVisual(); // Open drawing context and draw the image to the visual using (DrawingContext drawingContext = drawingVisual.RenderOpen()) { // Render the image and close drawing context drawingContext.DrawImage(imageSource, bitmapRect); } // Create render target bitmap and render the visual RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap((Int32)bitmapRect.Width, (Int32)bitmapRect.Height, 96.0d, 96.0d, PixelFormats.Pbgra32); renderTargetBitmap.Render(drawingVisual); renderTargetBitmap.Freeze(); // Create bitmap frame from the render target bitmap bitmapFrame = BitmapFrame.Create(renderTargetBitmap); } // Copy pixels from bitmap frame to pixel array Int32 stride = (bitmapFrame.Format.BitsPerPixel * bitmapFrame.PixelWidth + 31) / 32 * 4; Byte[] pixelArray = new Byte[stride * bitmapFrame.PixelHeight]; bitmapFrame.CopyPixels(pixelArray, stride, 0); // Mask & icon bitmap handles IntPtr maskBitmapPtr = IntPtr.Zero; IntPtr iconBitmapPtr = IntPtr.Zero; // Initialize BITMAPINFO/BITMAPINFOHEADER structure NativeMethods.BITMAPINFO bmi = new NativeMethods.BITMAPINFO(); bmi.bmiHeader.biSize = (UInt32)Marshal.SizeOf(typeof(NativeMethods.BITMAPINFOHEADER)); bmi.bmiHeader.biWidth = (Int32)bitmapRect.Width; bmi.bmiHeader.biHeight -= ((Int32)bitmapRect.Height); bmi.bmiHeader.biPlanes = 1; bmi.bmiHeader.biBitCount = (UInt16)bitmapFrame.Format.BitsPerPixel; // DIB handle IntPtr dibPtr = IntPtr.Zero; // Create icon bitmap DIB section iconBitmapPtr = NativeMethods.CreateDIBSection(IntPtr.Zero, ref bmi, 0, out dibPtr, IntPtr.Zero, 0); // Validate icon bitmap handle if (iconBitmapPtr != IntPtr.Zero && dibPtr != IntPtr.Zero) { // Copy pixels to unmanaged memory Marshal.Copy(pixelArray, 0, dibPtr, pixelArray.Length); // Create mask bitmap maskBitmapPtr = NativeMethods.CreateBitmap((Int32)bitmapRect.Width, (Int32)bitmapRect.Height, 1, 1, IntPtr.Zero); if (maskBitmapPtr != IntPtr.Zero) { // Create and initialize ICONINFO structure NativeMethods.ICONINFO iconInfo = new NativeMethods.ICONINFO(); iconInfo.fIcon = true; iconInfo.hbmMask = maskBitmapPtr; iconInfo.hbmColor = iconBitmapPtr; // Create icon handle IntPtr iconPtr = NativeMethods.CreateIconIndirect(ref iconInfo); if (iconPtr != IntPtr.Zero) { result = new IconHandle(iconPtr); } } } // Clean up resources if (maskBitmapPtr != IntPtr.Zero) { NativeMethods.DeleteObject(maskBitmapPtr); } if (iconBitmapPtr != IntPtr.Zero) { NativeMethods.DeleteObject(iconBitmapPtr); } } // Return result return(result); }
private void Timer_Elapsed(object sender, ElapsedEventArgs e) { Dispatcher.BeginInvoke((Action)(() => { //foreach (FieldInfo type in typeof(DataFormats).GetFields()) //{ // if (Clipboard.GetDataObject().GetDataPresent(type.GetValue("") as string)) // { // Console.WriteLine(type.GetValue("") as string); // } //} try { transfareData IDataTranfare = new transfareData(); foreach (string _supported in supportedFormats) { if (!Clipboard.GetDataObject().GetDataPresent(_supported)) { continue; } if (_supported == DataFormats.Bitmap) { Image image = new Image(); System.Windows.Interop.InteropBitmap interopBitmap = (System.Windows.Interop.InteropBitmap)Clipboard.GetImage(); image.Source = interopBitmap; IDataTranfare.copyValue = image; BitmapFrame interopBitmap1 = CreateResizedImage(interopBitmap, Math.Min(interopBitmap.PixelWidth, 100), Math.Min(interopBitmap.PixelHeight, 100), 0); Image image2 = new Image(); image2.Source = interopBitmap1; IDataTranfare.contentValue = image2; Int32Rect rect = new Int32Rect(0, 0, interopBitmap1.PixelWidth, interopBitmap1.PixelHeight); int stride = interopBitmap1.PixelWidth * (interopBitmap1.Format.BitsPerPixel + 7) / 8; int arrayLength = stride * interopBitmap1.PixelHeight; int[] arr = new int[arrayLength]; interopBitmap1.CopyPixels(rect, arr, stride, 0); unchecked { int sum = 0; for (int i = 0; i < arr.Length; i++) { sum += arr[i]; } IDataTranfare.savedValue = sum / arr.Length; } } else if (_supported == DataFormats.Text) { IDataTranfare.copyValue = Clipboard.GetText().Replace("\n", "").Replace("\r", ""); IDataTranfare.savedValue = IDataTranfare.copyValue; IDataTranfare.contentValue = IDataTranfare.copyValue; } IDataTranfare.format = _supported; break; } if (OLD_IData.Contains(IDataTranfare.savedValue) || IDataTranfare.format == null) { return; } OLD_IData.Add(IDataTranfare.savedValue); ListBOX.Items.Insert(0, new itemElement(ListBOX, OLD_IData, IDataTranfare)); } catch (Exception err) { Console.WriteLine(err); } })); }
public async Task <IImageData> Convert( MemoryStream s, int bitDepth, string rawType, ImageMetaData metaData, CancellationToken token = default) { return(await Task.Run(async() => { using (MyStopWatch.Measure()) { var fileextension = ".raw"; var filename = Path.GetRandomFileName(); var rawfile = Path.Combine(Utility.APPLICATIONTEMPPATH, filename + fileextension); using (var filestream = new System.IO.FileStream(rawfile, System.IO.FileMode.Create)) { s.WriteTo(filestream); } ImageData data = null; var outputFile = Path.Combine(Utility.APPLICATIONTEMPPATH, filename + ".tiff"); try { System.Diagnostics.Process process; System.Diagnostics.ProcessStartInfo startInfo; var sb = new StringBuilder(); using (MyStopWatch.Measure("DCRawStart")) { process = new System.Diagnostics.Process(); startInfo = new System.Diagnostics.ProcessStartInfo(); startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal; startInfo.FileName = DCRAWLOCATION; startInfo.UseShellExecute = false; startInfo.RedirectStandardOutput = true; startInfo.RedirectStandardError = true; startInfo.RedirectStandardInput = true; startInfo.CreateNoWindow = true; startInfo.Arguments = "-4 -d -T -t 0 -v \"" + rawfile + "\""; process.StartInfo = startInfo; process.EnableRaisingEvents = true; process.OutputDataReceived += (object sender, System.Diagnostics.DataReceivedEventArgs e) => { sb.AppendLine(e.Data); }; process.ErrorDataReceived += (object sender, System.Diagnostics.DataReceivedEventArgs e) => { sb.AppendLine(e.Data); }; process.Start(); process.BeginOutputReadLine(); process.BeginErrorReadLine(); await process.WaitForExitAsync(token); Logger.Trace(sb.ToString()); } using (MyStopWatch.Measure("DCRawReadIntoImageArray")) { if (File.Exists(outputFile)) { TiffBitmapDecoder TifDec = new TiffBitmapDecoder(new Uri(outputFile), BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad); BitmapFrame bmp = TifDec.Frames[0]; ushort[] pixels = new ushort[bmp.PixelWidth *bmp.PixelHeight]; bmp.CopyPixels(pixels, 2 * bmp.PixelWidth, 0); //Due to the settings of dcraw decoding the values will be stretched to 16 bits bitDepth = 16; var imageArray = new ImageArray(flatArray: pixels, rawData: s.ToArray(), rawType: rawType); data = new ImageData( imageArray: imageArray, width: (int)bmp.PixelWidth, height: (int)bmp.PixelHeight, bitDepth: bitDepth, isBayered: true, metaData: metaData); } else { Logger.Error("File not found: " + outputFile); throw new Exception("Error occured during DCRaw conversion." + Environment.NewLine + sb.ToString()); } } } catch (Exception ex) { Notification.Notification.ShowError(ex.Message); Logger.Error(ex); } finally { if (File.Exists(rawfile)) { File.Delete(rawfile); } if (File.Exists(outputFile)) { File.Delete(outputFile); } } return data; } })); }
/// <summary> /// Creates an Image with specified adjustments based on an image file on disk. /// </summary> /// <param name="angle">The angle to rotate the image. One of 0, 90, 180, or 270.</param> /// <param name="hueShift">The degrees to rotate the hue.</param> /// <param name="saturationAdjust">A value between -100 and 100. Negative values reduce saturation; positive values increase saturation.</param> /// <param name="lightnessAdjust">A value between -100 and 100. Negative values darken the color; positive values lighten the color.</param> /// <param name="contrast">A value between -100 and 100. Negative values reduce contrast (move more toward the threshold value); positive values increase the contrast (move away from the threshold value).</param> /// <param name="scaleX">The horizontal scale of the image.</param> /// <param name="scaleY">The vertical scale of the image.</param> /// <param name="fileName">The image file to load.</param> /// <returns></returns> public static Image CreateImage(int angle, double hueShift, double saturationAdjust, double lightnessAdjust, double contrast, double scaleX, double scaleY, string fileName) { TransformedBitmap transformBmp = new TransformedBitmap(); BitmapSource bitmapSource; if (hueShift == 0 && saturationAdjust == 0 && lightnessAdjust == 0 && contrast == 0) { BitmapImage bmpImage = new BitmapImage(); bmpImage.BeginInit(); bmpImage.UriSource = new Uri(fileName, UriKind.RelativeOrAbsolute); bmpImage.EndInit(); bitmapSource = bmpImage; } else { BitmapDecoder dec = BitmapDecoder.Create(new Uri(fileName), BitmapCreateOptions.None, BitmapCacheOption.Default); BitmapFrame firstFrame = dec.Frames[0]; const int bytesPerPixel = 4; int stride = firstFrame.PixelWidth * bytesPerPixel; byte[] pixels = new byte[stride * firstFrame.PixelHeight]; firstFrame.CopyPixels(pixels, stride, 0); for (int i = 0; i < pixels.Length / 4; ++i) { int index = i * 4; const int blueOffset = 0; const int greenOffset = 1; const int redOffset = 2; const int alphaOffset = 3; // Diagnostic pixel testing: //int y = i / firstFrame.PixelWidth; //int x = i - y * firstFrame.PixelWidth; //if (x == 229 && y == 254) //{ // System.Diagnostics.Debugger.Break(); //} byte b = pixels[index + blueOffset]; byte g = pixels[index + greenOffset]; byte r = pixels[index + redOffset]; byte a = pixels[index + alphaOffset]; if (a == 0) { continue; } HueSatLight hueSatLight = new HueSatLight(Color.FromArgb(a, r, g, b)); if (hueShift != 0) { hueSatLight.HueShiftDegrees(hueShift); } if (saturationAdjust != 0) { hueSatLight.AdjustSaturation(saturationAdjust); } if (lightnessAdjust != 0) { hueSatLight.AdjustLightness(lightnessAdjust); } if (contrast != 0) { hueSatLight.AdjustContrast(contrast, (lightnessAdjust + 100) / 200); } Color shifted = hueSatLight.AsRGB; pixels[index + blueOffset] = shifted.B; pixels[index + greenOffset] = shifted.G; pixels[index + redOffset] = shifted.R; pixels[index + alphaOffset] = shifted.A; } bitmapSource = CreateBitmap(firstFrame, stride, pixels); } transformBmp.BeginInit(); transformBmp.Source = bitmapSource; RotateTransform rotation = null; if (angle != 0) { rotation = new RotateTransform(angle); } ScaleTransform scaling = null; if (scaleX != 1 || scaleY != 1) { scaling = new ScaleTransform(scaleX, scaleY); } if (scaling != null || rotation != null) { TransformGroup group = new TransformGroup(); if (scaling != null) { group.Children.Add(scaling); } if (rotation != null) { group.Children.Add(rotation); } transformBmp.Transform = group; } transformBmp.EndInit(); Image result = new Image(); result.Source = transformBmp; return(result); }
public static Image CreateImage(int angle, double hueShift, double saturationAdjust, double lightnessAdjust, double contrast, double scaleX, double scaleY, string fileName) { TransformedBitmap transformBmp = new TransformedBitmap(); BitmapSource bitmapSource; if (hueShift == 0 && saturationAdjust == 0 && lightnessAdjust == 0 && contrast == 0) { BitmapImage bmpImage = new BitmapImage(); bmpImage.BeginInit(); bmpImage.UriSource = new Uri(fileName, UriKind.RelativeOrAbsolute); bmpImage.EndInit(); bitmapSource = bmpImage; } else { BitmapDecoder dec = BitmapDecoder.Create(new Uri(fileName), BitmapCreateOptions.None, BitmapCacheOption.Default); BitmapFrame firstFrame = dec.Frames[0]; const int bytesPerPixel = 4; byte[] pixels = new byte[firstFrame.PixelWidth * firstFrame.PixelHeight * bytesPerPixel]; firstFrame.CopyPixels(pixels, firstFrame.PixelWidth * bytesPerPixel, 0); for (int i = 0; i < pixels.Length / 4; ++i) { int index = i * 4; const int blueOffset = 0; const int greenOffset = 1; const int redOffset = 2; const int alphaOffset = 3; byte b = pixels[index + blueOffset]; byte g = pixels[index + greenOffset]; byte r = pixels[index + redOffset]; byte a = pixels[index + alphaOffset]; HueSatLight hueSatLight = new HueSatLight(Color.FromArgb(a, r, g, b)); if (hueShift != 0) { hueSatLight.HueShiftDegrees(hueShift); } if (saturationAdjust != 0) { hueSatLight.AdjustSaturation(saturationAdjust); } if (lightnessAdjust != 0) { hueSatLight.AdjustLightness(lightnessAdjust); } if (contrast != 0) { hueSatLight.AdjustContrast(contrast, (lightnessAdjust + 100) / 200); } Color shifted = hueSatLight.AsRGB; pixels[index + blueOffset] = shifted.B; pixels[index + greenOffset] = shifted.G; pixels[index + redOffset] = shifted.R; pixels[index + alphaOffset] = shifted.A; } // Write the modified pixels into a new bitmap and set that to the source var writeableBitmap = new WriteableBitmap(firstFrame.PixelWidth, firstFrame.PixelHeight, firstFrame.DpiX, firstFrame.DpiY, PixelFormats.Pbgra32, null); writeableBitmap.WritePixels(new Int32Rect(0, 0, firstFrame.PixelWidth, firstFrame.PixelHeight), pixels, firstFrame.PixelWidth * bytesPerPixel, 0); bitmapSource = writeableBitmap; } transformBmp.BeginInit(); transformBmp.Source = bitmapSource; RotateTransform rotation = new RotateTransform(angle); ScaleTransform scaling = new ScaleTransform(scaleX, scaleY); TransformGroup group = new TransformGroup(); group.Children.Add(scaling); group.Children.Add(rotation); transformBmp.Transform = group; transformBmp.EndInit(); Image result = new Image(); result.Source = transformBmp; return(result); }
internal static (Image Image, ImageMetadata Metadata) FromBitmapFrame(this BitmapFrame bitmapFrame) { if (bitmapFrame == null) { throw new ArgumentNullException(nameof(bitmapFrame)); } int?xres = null; int?yres = null; // load metadata ImageMetadata metadata = null; if (bitmapFrame.Metadata is BitmapMetadata bitmapMetadata) { metadata = BitmapExtensions.ReadBitmapMetadata(bitmapMetadata); // reset resolution to 200 dpi for images that do not have resolution tag if (bitmapFrame.Decoder is TiffBitmapDecoder) { if (!metadata.HasPropertyItem((int)TIFFField.XResolution)) { xres = 200; } if (!metadata.HasPropertyItem((int)TIFFField.YResolution)) { yres = 200; } } // remove standard tags metadata.RemovePropertyItems(x => x.Id == (int)TIFFField.ImageWidth || x.Id == (int)TIFFField.ImageLength || x.Id == (int)TIFFField.XResolution || x.Id == (int)TIFFField.YResolution || x.Id == (int)TIFFField.BitsPerSample); } // verify palette presence System.Windows.Media.PixelFormat pixelFormat = bitmapFrame.Format; if ((pixelFormat == PixelFormats.Indexed1 || pixelFormat == PixelFormats.Indexed2 || pixelFormat == PixelFormats.Indexed4 || pixelFormat == PixelFormats.Indexed8) && bitmapFrame.Palette?.Colors == null) { throw new InvalidOperationException(Properties.Resources.E_UnsupportedImageFormat); } // load image Image image = new Image( bitmapFrame.PixelWidth, bitmapFrame.PixelHeight, pixelFormat.BitsPerPixel, xres.GetValueOrDefault((int)(bitmapFrame.DpiX + 0.5f)), yres.GetValueOrDefault((int)(bitmapFrame.DpiY + 0.5f))); int strideInBytes = (((image.Width * image.BitsPerPixel) + 31) & ~31) >> 3; uint[] bits = new uint[image.Height * strideInBytes / sizeof(uint)]; bitmapFrame.CopyPixels(bits, strideInBytes, 0); unsafe { fixed(uint *src = bits) { fixed(ulong *dst = image.Bits) { Arrays.CopyStrides( image.Height, new IntPtr(src), strideInBytes, new IntPtr(dst), image.Stride8); } } } if (image.BitsPerPixel < 8) { Vectors.SwapBits(image.Bits.Length, image.BitsPerPixel, image.Bits, 0); } // special case for BitmapFrame BlackWhite pixel format if (bitmapFrame.Format == PixelFormats.BlackWhite) { image.Not(image); metadata.RemovePropertyItem((int)TIFFField.PhotometricInterpretation); } return( Image.OnLoaded( image, metadata, bitmapFrame.Palette?.Colors?.Select(x => Color.FromArgb(x.A, x.R, x.G, x.B)).ToArray()), metadata); }
public void CompareImages(bool createDiffImage) { using (Stream leftStream = new FileStream(leftImagePath, FileMode.Open, FileAccess.Read, FileShare.Read)) { BitmapFrame leftFrame = GetBitmapFrame(leftImagePath, leftStream); int leftHeight = leftFrame.PixelHeight; int leftWidth = leftFrame.PixelWidth; int leftBytesPerPixel = (leftFrame.Format.BitsPerPixel + 7) / 8; int leftStride = leftWidth * leftBytesPerPixel; byte[] leftBytes = new byte[leftHeight * leftStride]; leftFrame.CopyPixels(leftBytes, leftStride, 0); using (Stream rightStream = new FileStream(rightImagePath, FileMode.Open, FileAccess.Read, FileShare.Read)) { BitmapFrame rightFrame = GetBitmapFrame(rightImagePath, rightStream); int rightHeight = rightFrame.PixelHeight; int rightWidth = rightFrame.PixelWidth; int rightBytesPerPixel = (rightFrame.Format.BitsPerPixel + 7) / 8; int rightStride = rightWidth * rightBytesPerPixel; byte[] rightBytes = new byte[rightHeight * rightStride]; rightFrame.CopyPixels(rightBytes, rightStride, 0); if (rightFrame.Format != leftFrame.Format) { throw new InvalidDataException("Images not the same format(" + leftFrame.Format.ToString() + " != " + rightFrame.Format.ToString()); } int diffHeight = Math.Min(leftHeight, rightHeight); int diffWidth = Math.Min(leftWidth, rightWidth); int diffStride = diffWidth * leftBytesPerPixel; int pixelCount = diffHeight * diffStride; double totalAbsoluteDifference = 0; double totalSquareDifference = 0; int[] diffInts = null; if (createDiffImage) { diffInts = new int[leftHeight * leftStride]; } int maxDiff = 0; for (int row = 0; row < diffHeight; ++row) { for (int col = 0; col < diffStride; ++col) { int difference = rightBytes[col + row * rightStride] - leftBytes[col + row * leftStride]; totalAbsoluteDifference += Math.Abs(difference); totalSquareDifference += difference * difference; if (createDiffImage) { diffInts[col + row * diffStride] = difference; } if (difference > maxDiff) { maxDiff = difference; } else if (difference < -maxDiff) { maxDiff = (short)-difference; } } } if (createDiffImage) { byte[] diffBytes = new byte[leftHeight * leftStride]; double scale = 1; if (maxDiff != 0) { scale = 127.0 / (double)maxDiff; } for (int i = 0; i < diffInts.Length; ++i) { diffBytes[i] = (byte)((double)diffInts[i] * scale + 128.0); } Result = BitmapSource.Create(diffWidth, diffHeight, leftFrame.DpiX, leftFrame.DpiY, leftFrame.Format, null, diffBytes, diffStride); } AverageAbsoluteDifference = (totalAbsoluteDifference / (double)pixelCount); AverageSquareDifference = (totalSquareDifference / (double)pixelCount); } } }
public static byte[] ImageToBinary(BitmapFrame frame) { byte[] data = new byte[frame.PixelWidth * frame.PixelHeight]; frame.CopyPixels(data, frame.PixelWidth, 0); return(data); }