コード例 #1
0
		public static UIImage BufferToImage (Color[] buffer, int width, int height)
		{
			byte[] bytes = new byte[buffer.Length * 4];
			int j = 0;
			for (int i=0; i<buffer.Length; i++, j+= 4) {
				bytes[j+0] = buffer[i].R;
				bytes[j+1] = buffer[i].G;
				bytes[j+2] = buffer[i].B;
				bytes[j+3] = 255;
			}
			CGDataProvider dataProvider = new CGDataProvider(bytes, 0, bytes.Length);
			CGImage image = new CGImage(
				width, 
				height, 
				8, 
				32, 
				4 * width, 
				CGColorSpace.CreateDeviceRGB(), 
				CGBitmapFlags.ByteOrderDefault | CGBitmapFlags.Last, 
				dataProvider, 
				null, 
				false, 
				CGColorRenderingIntent.Default
			);
			return new UIImage(image);
		}
        void initialize()
        {
            _fps = 0;            
            _path = null;

            Frame = new System.Drawing.RectangleF(0, 0, 320, 480 - 54);
            // important - it needs to be transparent so the camera preview shows through!
            Opaque = false;
            BackgroundColor = UIColor.Clear;

            // allocating bitmap buffer
            _buffer     = new RawBitmap((int)Frame.Width, (int)Frame.Height);
            _drawnImage = new RawBitmap((int)Frame.Width, (int)Frame.Height);
            // creating checkerboard mask image
            using (var checkerBoardImage = new RawBitmap((int)Bounds.Size.Width, (int)Bounds.Size.Height))
            {
                for (int y = 0; y < checkerBoardImage.Height; y += 2)
                {
                    for (int x = 0; x < checkerBoardImage.Width; x += 2)
                    {
                        checkerBoardImage.WritePixel(x, y, 255);                        
                    }
                }
                for (int y = 1; y < checkerBoardImage.Height; y += 2)
                {
                    for (int x = 1; x < checkerBoardImage.Width; x += 2)
                    {
                        checkerBoardImage.WritePixel(x, y, 255);
                    }
                }
                _maskImage = checkerBoardImage.Context.ToImage();
			}
		}
コード例 #3
0
        /// <summary>
        /// バイト配列からWriteableBitmapを生成する
        /// </summary>
        /// <param name="width">幅</param>
        /// <param name="height">高さ</param>
        /// <param name="array">ピクセルデータ</param>
        /// <returns>WriteableBitmapオブジェクト</returns>
        public static UIImage FromArray(this UIImage bmp, byte[] array)
        {
            var cgImage = bmp.CGImage;

	        int width = cgImage.Width;
	        int height = cgImage.Height;
	        int bitsPerComponent = cgImage.BitsPerComponent;
	        int bitsPerPixel = cgImage.BitsPerPixel;
	        int bytesPerRow = cgImage.BytesPerRow;
	        var colorSpace = cgImage.ColorSpace;
	        var bitmapInfo = cgImage.BitmapInfo;
	        var shouldInterpolate = cgImage.ShouldInterpolate;
	        var intent = cgImage.RenderingIntent; 

            // 画像処理後のbyte配列を元にデータプロバイダーを作成する
            CGImage effectedCgImage;

            using (var effectedDataProvider = new CGDataProvider(array, 0, array.Length))
            {
                // データプロバイダーからCGImageを作成し、CGImageからUIImageを作成する
                effectedCgImage = new CGImage(
                    width, height, bitsPerComponent, bitsPerPixel, bytesPerRow,
                    colorSpace, bitmapInfo, effectedDataProvider,
                    null, shouldInterpolate, intent);
            }
            
            return new UIImage(effectedCgImage);
        }
コード例 #4
0
		public System.IO.Stream RenderToStream (byte[] documentData, int pageIndex)
		{
			using (MemoryStream ms = new MemoryStream (documentData))
			{
				// open document
				using (Document doc = new Document (ms)) 
				{
					// prepare for rendering
					int width = (int)doc.Pages [pageIndex].Width;
					int height = (int)doc.Pages [pageIndex].Height;
					// render the page to a raw bitmap data represented by byte array
					byte[] imageData = ConvertBGRAtoRGBA(doc.Pages [pageIndex].RenderAsBytes (width,height, new RenderingSettings (), null));

					// create CGDataProvider which will serve CGImage creation
					CGDataProvider dataProvider = new CGDataProvider (imageData, 0, imageData.Length);

					// create core graphics image using data provider created above, note that
					// we use CGImageAlphaInfo.Last(ARGB) pixel format
					CGImage cgImage = new CGImage(width,height,8,32,width*4,CGColorSpace.CreateDeviceRGB(),CGImageAlphaInfo.Last,dataProvider,null,false, CGColorRenderingIntent.Default);

					// create UIImage and save it to gallery
					UIImage finalImage = new UIImage (cgImage);
								
					return finalImage.AsPNG ().AsStream();
				}
			}						
		}
コード例 #5
0
 public Bitmap(string filename)
 {
     //
     // This is a quick hack: we should use ImageIO to load the data into
     // memory, so we always have the bitmapBlock availabe
     //
     var uiimage = UIImage.FromFileUncached (filename);
     NativeCGImage = uiimage.CGImage;
 }
コード例 #6
0
 void SaveToRequest (CGImage image, string typeIdentifier, Request request)
 {
     if (request is FileRequest)
         SaveToFile (image, typeIdentifier, (FileRequest) request);
     else if (request is MemoryRequest)
         SaveToMemory (image, (MemoryRequest) request);
     else
         throw new NotImplementedException ();
 }
コード例 #7
0
		/// <summary>
		/// Trigger the ImageCaptured event.
		/// </summary>
		/// <param name="image">Image.</param>
		void OnImageCaptured( CGImage image )
		{
			var handler = this.ImageCaptured;
			if ( handler != null )
			{
				var args = new ImageCaptureEventArgs();
				args.Image = image;
				args.CapturedAt = DateTime.Now;
				handler( this, args );
			}
		}
コード例 #8
0
        void SaveToFile (CGImage image, string typeIdentifier, FileRequest request)
        {
            CheckImageArgument (image, "image");

            using (var thumbnail = new UIImage (image))
            using (var data = SerializeImage (thumbnail, typeIdentifier)) {
                NSError err;

                data.Save (NSUrl.FromFilename (request.Filename), false, out err);

                if (err != null)
                    throw new Exception (err.ToString ());
            }
        }
コード例 #9
0
ファイル: Image.cs プロジェクト: CBrauer/monotouch-samples
		static CGImage Crop (CGImage rawImage)
		{
			// Crops from top and bottom evenly
			var h = rawImage.Height;
			var w = rawImage.Width;

			if (h > w) {
				var offset = (h - w) / 2;
				return rawImage.WithImageInRect (new CGRect (0, offset, w, w));
			} else {
				var offset = (w - h) / 2;
				return rawImage.WithImageInRect (new CGRect (offset, 0, h, h));
			}
		}
コード例 #10
0
ファイル: MatiOS.cs プロジェクト: neutmute/emgucv
 private void ConvertFromCGImage(CGImage cgImage)
 {
    Size sz = new Size((int) cgImage.Width, (int) cgImage.Height);
    using (Mat m = new Mat(sz, DepthType.Cv8U, 4))
    {
       RectangleF rect = new RectangleF(PointF.Empty, new SizeF(cgImage.Width, cgImage.Height));
       using (CGColorSpace cspace = CGColorSpace.CreateDeviceRGB())
       using (CGBitmapContext context = new CGBitmapContext(
        m.DataPointer,             
        sz.Width, sz.Height,
        8,
        sz.Width * 4,
        cspace,
        CGImageAlphaInfo.PremultipliedLast))
          context.DrawImage(rect, cgImage);
       CvInvoke.CvtColor(m, this, ColorConversion.Rgba2Bgr);
    } 
 }
コード例 #11
0
		public override void ViewDidLoad ()
		{
			base.ViewDidLoad ();

			var w = 100;
			var h = 100;
			var componentNum = 4; // RGBA
			var bytesPerRow = w * componentNum;
			var bitsPerComponent = 8;
			var data = new byte [bytesPerRow * h];
			for (int x = 0; x < 100; x++) {
				for (int y = 0; y < 100; y++) {
					data [y * bytesPerRow + componentNum * x + 3] = 255;
				}
			}
			var provider = new CGDataProvider (data);
			var img = new CGImage (w, h, bitsPerComponent, bitsPerComponent * componentNum, bytesPerRow, CGColorSpace.CreateDeviceRGB (), CGBitmapFlags.Last, provider, null, false, CGColorRenderingIntent.Default);
			MyImage.Image = new NSImage (img, new CGSize (w, h));
		}
コード例 #12
0
        private void ConvertFromCGImage(CGImage cgImage)
        {
            Size sz = new Size((int)cgImage.Width, (int)cgImage.Height);

            using (Mat m = new Mat(sz, DepthType.Cv8U, 4))
            {
                RectangleF rect = new RectangleF(PointF.Empty, new SizeF(cgImage.Width, cgImage.Height));
                using (CGColorSpace cspace = CGColorSpace.CreateDeviceRGB())
                    using (CGBitmapContext context = new CGBitmapContext(
                               m.DataPointer,
                               sz.Width, sz.Height,
                               8,
                               sz.Width * 4,
                               cspace,
                               CGImageAlphaInfo.PremultipliedLast))
                        context.DrawImage(rect, cgImage);
                CvInvoke.CvtColor(m, this, ColorConversion.Rgba2Bgr);
            }
        }
コード例 #13
0
ファイル: Image.iOS.cs プロジェクト: masums/Uno
        private void SetImageFromWriteableBitmap(WriteableBitmap writeableBitmap)
        {
            if (writeableBitmap.PixelBuffer is InMemoryBuffer memoryBuffer)
            {
                // Convert RGB colorspace.
                var bgraBuffer = memoryBuffer.Data;
                var rgbaBuffer = new byte[memoryBuffer.Data.Length];

                for (int i = 0; i < memoryBuffer.Data.Length; i += 4)
                {
                    rgbaBuffer[i + 3] = bgraBuffer[i + 3];                     // a
                    rgbaBuffer[i + 0] = bgraBuffer[i + 2];                     // r
                    rgbaBuffer[i + 1] = bgraBuffer[i + 1];                     // g
                    rgbaBuffer[i + 2] = bgraBuffer[i + 0];                     // b
                }

                using (var dataProvider = new CGDataProvider(rgbaBuffer, 0, rgbaBuffer.Length))
                {
                    using (var colorSpace = CGColorSpace.CreateDeviceRGB())
                    {
                        var bitsPerComponent = 8;
                        var bytesPerPixel    = 4;

                        using (var cgImage = new CGImage(
                                   writeableBitmap.PixelWidth,
                                   writeableBitmap.PixelHeight,
                                   bitsPerComponent,
                                   bitsPerComponent * bytesPerPixel,
                                   bytesPerPixel * writeableBitmap.PixelWidth,
                                   colorSpace,
                                   CGImageAlphaInfo.Last,
                                   dataProvider,
                                   null,
                                   false,
                                   CGColorRenderingIntent.Default
                                   ))
                        {
                            SetImage(UIImage.FromImage(cgImage));
                        }
                    }
                }
            }
        }
コード例 #14
0
ファイル: AppleExtensions.cs プロジェクト: tro476/SkiaSharp
        public static CGImage ToCGImage(this SKPixmap skiaPixmap)
        {
            var info = skiaPixmap.Info;

            CGImage cgImage;

            using (var provider = new CGDataProvider(skiaPixmap.GetPixels(), info.BytesSize))
                using (var colorSpace = CGColorSpace.CreateDeviceRGB())
                {
                    cgImage = new CGImage(
                        info.Width, info.Height,
                        8, info.BitsPerPixel, info.RowBytes,
                        colorSpace,
                        CGBitmapFlags.PremultipliedLast | CGBitmapFlags.ByteOrder32Big,
                        provider,
                        null, false, CGColorRenderingIntent.Default);
                }
            return(cgImage);
        }
コード例 #15
0
        public void FromPNG()
        {
            string file = Path.Combine(NSBundle.MainBundle.ResourcePath, "basn3p08.png");

            using (var dp = new CGDataProvider(file))
                using (var img = CGImage.FromPNG(dp, null, false, CGColorRenderingIntent.Default))
#if MONOMAC
                    using (var ui = new NSImage(img, new CGSize(10, 10))) {
#else
                    using (var ui = new UIImage(img, 1.0f, UIImageOrientation.Up)) {
#endif
                        Assert.IsNotNull(ui.CGImage, "CGImage");
                        if (TestRuntime.CheckXcodeVersion(7, 0))
                        {
                            Assert.That(img.UTType.ToString(), Is.EqualTo("public.png"), "UTType");
                        }
                    }
        }
    }
コード例 #16
0
ファイル: TwittView.cs プロジェクト: Molnia107/twitterBot
        public TwittView()
        {
            _backgroundImageView = new UIImageView();
            _userNameLabel       = ViewFactory.CreateUILabel();
            _userMaskImageView   = new UIImageView();
            _viaLabel            = ViewFactory.CreateUILabel();
            _twittTextLabel      = ViewFactory.CreateUILabel();
            _lineImageView       = new UIImageView();
            _twittDateLabel      = ViewFactory.CreateUILabel();
            _twittUrlLabel       = ViewFactory.CreateUILabel();

            AddSubview(_backgroundImageView);
            AddSubview(_userNameLabel);
            AddSubview(_viaLabel);
            AddSubview(_twittTextLabel);
            AddSubview(_lineImageView);
            AddSubview(_twittDateLabel);
            AddSubview(_twittUrlLabel);
            AddSubview(_userMaskImageView);

            _backgroundImageView.Image = UIImage.FromFile(ImagePathes.TwittBg);

            _userNameLabel.Font      = UIFont.BoldSystemFontOfSize(14);
            _userNameLabel.TextColor = UIColor.FromRGB(69, 99, 141);

            _viaLabel.Font = UIFont.BoldSystemFontOfSize(12);

            _twittTextLabel.Font = UIFont.SystemFontOfSize(12);

            _twittTextLabel.LineBreakMode = UILineBreakMode.WordWrap;
            _twittTextLabel.Lines         = 0;

            _lineImageView.Image = UIImage.FromFile(ImagePathes.Line);
            _lineImageView.SizeToFit();

            _twittDateLabel.Font      = UIFont.SystemFontOfSize(10);
            _twittDateLabel.TextColor = UIColor.FromRGB(123, 123, 123);

            _userMaskImageView.Frame = new RectangleF(0, 0, 72, 72);
            var maskImg = UIImage.FromFile(ImagePathes.MaskAvatar).CGImage;

            _mask = CGImage.CreateMask(maskImg.Width, maskImg.Height, maskImg.BitsPerComponent, maskImg.BitsPerPixel, maskImg.BytesPerRow, maskImg.DataProvider, null, true);
        }
コード例 #17
0
        void SetupPattern(CGContextBackend gc)
        {
            gc.Context.SetPatternPhase(new CGSize(0, 0));

            if (gc.CurrentStatus.Pattern is GradientInfo)
            {
                return;
            }

            if (gc.CurrentStatus.Pattern is ImagePatternInfo)
            {
                var pi     = (ImagePatternInfo)gc.CurrentStatus.Pattern;
                var bounds = new CGRect(CGPoint.Empty, new CGSize(pi.Image.Size.Width, pi.Image.Size.Height));
                var t      = CGAffineTransform.Multiply(CGAffineTransform.MakeScale(1f, -1f), gc.Context.GetCTM());

                CGPattern pattern;
                if (pi.Image is CustomImage)
                {
                    pattern = new CGPattern(bounds, t, bounds.Width, bounds.Height, CGPatternTiling.ConstantSpacing, true, c => {
                        c.TranslateCTM(0, bounds.Height);
                        c.ScaleCTM(1f, -1f);
                        ((CustomImage)pi.Image).DrawInContext(c);
                    });
                }
                else
                {
                    var     empty = CGRect.Empty;
                    CGImage cgimg = pi.Image.AsCGImage(ref empty, null, null);
                    pattern = new CGPattern(bounds, t, bounds.Width, bounds.Height,
                                            CGPatternTiling.ConstantSpacing, true, c => c.DrawImage(bounds, cgimg));
                }

                using (pattern)
                {
                    CGContext ctx   = gc.Context;
                    var       alpha = new[] { (nfloat)pi.Alpha };
                    ctx.SetFillColorSpace(Util.PatternColorSpace);
                    ctx.SetStrokeColorSpace(Util.PatternColorSpace);
                    ctx.SetFillPattern(pattern, alpha);
                    ctx.SetStrokePattern(pattern, alpha);
                }
            }
        }
コード例 #18
0
        public Bitmap(UIImage image)
        {
            _backingImage = image;
            CGImage imageRef = _backingImage.CGImage;

            Width  = imageRef.Width;
            Height = imageRef.Height;
            CGColorSpace colorSpace = CGColorSpace.CreateDeviceRGB();

            rawData = Marshal.AllocHGlobal(Height * Width * 4);
            CGContext context = new CGBitmapContext(
                rawData, Width, Height, 8, 4 * Width, colorSpace, CGImageAlphaInfo.PremultipliedLast
                );

            context.DrawImage(new RectangleF(0.0f, 0.0f, (float)Width, (float)Height), imageRef);

            pixelData = new byte[Height * Width * 4];
            Marshal.Copy(rawData, pixelData, 0, pixelData.Length);
        }
コード例 #19
0
        public static void setCurrentPhotoToIndex(int index)
        {
            currentAsset = photoAssets [index];
            ALAssetRepresentation rep = currentAsset.RepresentationForUti("public.jpeg");

            // image might not be available as a JPEG
            if (rep == null)
            {
                return;
            }
            CGImage imageRef = rep.GetFullScreenImage();

            if (imageRef == null)
            {
                return;
            }
            currentPhotoImage = UIImage.FromImage(imageRef);
            currentPhotoIndex = index;
        }
コード例 #20
0
ファイル: iOSSurfaceSaver.cs プロジェクト: RUSshy/ultraviolet
 /// <summary>
 /// Saves the specified color data as an image using the specified encoding.
 /// </summary>
 /// <param name="data">An array containing the image's color data.</param>
 /// <param name="width">The width of the image in pixels.</param>
 /// <param name="height">The height of the image in pixels.</param>
 /// <param name="stream">The stream to which to save the image data.</param>
 /// <param name="encoder">A function which produces an encoded data stream for the image.</param>
 private unsafe void Save(Color[] data, Int32 width, Int32 height, Stream stream, Func<UIImage, NSData> encoder)
 {
     fixed (Color* pdata = data)
     {
         using (var cgColorSpace = CGColorSpace.CreateDeviceRGB())
         using (var cgDataProvider = new CGDataProvider((IntPtr)pdata, sizeof(Color) * width * height, false))
         using (var cgImage = new CGImage(width, height, 8, 32, width * 4, cgColorSpace, CGBitmapFlags.PremultipliedLast, cgDataProvider, null, false, CGColorRenderingIntent.Default))
         {
             using (var img = UIImage.FromImage(cgImage))
             {
                 using (var imgData = encoder(img))
                 using (var imgStream = imgData.AsStream())
                 {
                     imgStream.CopyTo(stream);
                 }
             }
         }
     }
 }
コード例 #21
0
ファイル: BitmapHandler.cs プロジェクト: modulexcite/Eto-1
        public void Create(int width, int height, PixelFormat pixelFormat)
        {
            switch (pixelFormat)
            {
            case PixelFormat.Format32bppRgb:
            {
                int numComponents    = 4;
                int bitsPerComponent = 8;
                int bitsPerPixel     = numComponents * bitsPerComponent;
                int bytesPerPixel    = bitsPerPixel / 8;
                bytesPerRow = bytesPerPixel * width;
                Data        = new NSMutableData((uint)(bytesPerRow * height));

                provider = new CGDataProvider(Data.MutableBytes, (int)Data.Length, false);
                cgimage  = new CGImage(width, height, bitsPerComponent, bitsPerPixel, bytesPerRow, CGColorSpace.CreateDeviceRGB(), CGBitmapFlags.ByteOrder32Little | CGBitmapFlags.PremultipliedFirst, provider, null, true, CGColorRenderingIntent.Default);
                Control  = UIImage.FromImage(cgimage);

                break;
            }

            case PixelFormat.Format24bppRgb:
            {
                int numComponents    = 3;
                int bitsPerComponent = 8;
                int bitsPerPixel     = numComponents * bitsPerComponent;
                int bytesPerPixel    = bitsPerPixel / 8;
                bytesPerRow = bytesPerPixel * width;
                Data        = new NSMutableData((uint)(bytesPerRow * height));

                provider = new CGDataProvider(Data.MutableBytes, (int)Data.Length, false);
                cgimage  = new CGImage(width, height, bitsPerComponent, bitsPerPixel, bytesPerRow, CGColorSpace.CreateDeviceRGB(), CGBitmapFlags.ByteOrder32Little | CGBitmapFlags.PremultipliedFirst, provider, null, true, CGColorRenderingIntent.Default);
                Control  = UIImage.FromImage(cgimage);
                break;
            }

            /*case PixelFormat.Format16bppRgb555:
             *              control = new Gdk.Pixbuf(Gdk.Colorspace.Rgb, false, 5, width, height);
             *              break;*/
            default:
                throw new ArgumentOutOfRangeException("pixelFormat", pixelFormat, "Not supported");
            }
        }
コード例 #22
0
        /// <summary>
        /// Gets called by the video session if a new image is available.
        /// </summary>
        /// <param name="captureOutput">Capture output.</param>
        /// <param name="sampleBuffer">Sample buffer.</param>
        /// <param name="connection">Connection.</param>
        public override void DidOutputSampleBuffer(AVCaptureOutput captureOutput, CMSampleBuffer sampleBuffer, AVCaptureConnection connection)
        {
            System.Diagnostics.Debug.WriteLine("12345");
            try
            {
                // Convert the raw image data into a CGImage.
                using (CGImage sourceImage = GetImageFromSampleBuffer(sampleBuffer))
                {
                    this.OnImageCaptured(sourceImage);
                }

                // Make sure AVFoundation does not run out of buffers
                sampleBuffer.Dispose();
            }
            catch (Exception ex)
            {
                string errorMessage = string.Format("Failed to process image capture: {0}", ex);
                this.OnCaptureError(errorMessage, ex);
            }
        }
コード例 #23
0
 private void Transform(IntPtr buffer, byte[] bytes, int width, int height)
 {
     try
     {
         var space    = CGColorSpace.CreateDeviceRGB();
         var provider = new CGDataProvider(bytes);
         //var provider = new CGDataProvider(buffer);
         //var i = new CGImage(64, 64, 8, 24, 64 * 3, space, CGBitmapFlags.ByteOrderDefault, provider, null, false, CGColorRenderingIntent.Default);
         var i       = new CGImage(width, height, 8, 24, width * 3, space, CGBitmapFlags.ByteOrderDefault, provider, null, false, CGColorRenderingIntent.Default);
         var nsImage = new NSImage(i, new CGSize(width, height));
         Platform.UIInvoke(CoreDispatcherPriority.Normal, () =>
         {
             ((MediaElementCore.Parent) as MediaElement).ImageView.Image = nsImage;
         });
     }
     catch (Exception e)
     {
         Console.WriteLine(e);
     }
 }
コード例 #24
0
        public void InitializationWithCustomMetadata()
        {
            string file = Path.Combine(NSBundle.MainBundle.ResourcePath, "basn3p08.png");

            using (var dp = new CGDataProvider(file)) {
                using (var img = CGImage.FromPNG(dp, null, false, CGColorRenderingIntent.Default)) {
                    var opt = new CIImageInitializationOptionsWithMetadata()
                    {
                        Properties = new CGImageProperties()
                        {
                            ProfileName = "test profile name"
                        }
                    };

                    using (var ci = new CIImage(img, opt)) {
                        Assert.AreEqual("test profile name", ci.Properties.ProfileName);
                    }
                }
            }
        }
コード例 #25
0
ファイル: ScanView.cs プロジェクト: msioen/MenuBarCodeReader
        void ScanClick(CGRect bounds)
        {
            var rect = NSScreen.MainScreen.Frame;

            rect.Width  = this.Bounds.Width;
            rect.Height = this.Bounds.Height;
            rect.Y      = 0;

            IntPtr imageRef = CGWindowListCreateImage(rect, CGWindowListOption.OnScreenBelowWindow, (uint)Window.WindowNumber, CGWindowImageOption.Default);
            var    cgImage  = new CGImage(imageRef);

#if DEBUG
            //DebugHelperSaveImageToDisk(cgImage, "screen.png");
#endif

            bounds.Inflate(50, 50);

            var scanResults = DetectAndDecodeImage(cgImage, bounds);
            HandleDecodeResults(!string.IsNullOrWhiteSpace(scanResults.output) ? scanResults.bounds : bounds, scanResults.output);
        }
コード例 #26
0
        public static SKColor GetPixel(this CGImage cgImage, int x, int y)
        {
            var data = cgImage.DataProvider.CopyData();

            var bytesPerPixel = cgImage.BitsPerPixel / cgImage.BitsPerComponent;

            var offset = (y * cgImage.BytesPerRow) + (x * bytesPerPixel);

            var a = data[offset + 3];
            var r = data[offset + 0];
            var g = data[offset + 1];
            var b = data[offset + 2];

            if (a == 0)
            {
                return(SKColor.Empty);
            }

            return((SKColor) new SKColorF((float)r / a, (float)g / a, (float)b / a, a / 255f));
        }
コード例 #27
0
        public byte[] GetImageStreamFromPixels(byte[] pixelData, int width, int height)
        {
            byte[] streamData;

            using (CGColorSpace colorSpace = CGColorSpace.CreateDeviceRGB())
            {
                using (CGBitmapContext bitmapContext = new CGBitmapContext(pixelData, width, height, 8, 4 * width, colorSpace, CGBitmapFlags.ByteOrder32Big | CGBitmapFlags.PremultipliedLast))
                {
                    CGImage      cgImage = bitmapContext.ToImage();
                    UIImage      uiImage = new UIImage(cgImage);
                    NSData       nsData  = uiImage.AsPNG();
                    MemoryStream stream  = new MemoryStream();
                    nsData.AsStream().CopyTo(stream);
                    streamData = stream.ToArray();
                    stream.Dispose();
                }
            }

            return(streamData);
        }
コード例 #28
0
        public IUGContext CreateDrawingSession()
        {
            var bpp        = 8;
            var width      = (nint)(Scale * Width + .5F);
            var height     = (nint)(Scale * Height + .5F);
            var stride     = 4 * width;
            var canvasRect = new CGRect(0F, 0F, Width, Height);

            using (var colorSpace = CGColorSpace.CreateSrgb())
            {
                var context = new CGBitmapContext(null, width, height, bpp, stride, colorSpace, CGImageAlphaInfo.PremultipliedFirst);
                context.ScaleCTM(Scale, Scale);
                return(new UGContext(context, canvasRect, Scale, () =>
                {
                    _native = context.ToImage();
                    context.Dispose();
                    context = null;
                }));
            }
        }
コード例 #29
0
        private void CopyColorsFromImage(UIImage image)
        {
            var handle = GCHandle.Alloc(colors, GCHandleType.Pinned);

            using (CGImage cgimage = image.CGImage)
                using (CGColorSpace cspace = CGColorSpace.CreateDeviceRGB())
                    using (CGBitmapContext context = new CGBitmapContext(
                               handle.AddrOfPinnedObject(),
                               (nint)image.Size.Width,
                               (nint)image.Size.Height,
                               8,
                               (nint)image.Size.Width * 4,
                               cspace,
                               CGImageAlphaInfo.PremultipliedLast))
                    {
                        context.DrawImage(new CGRect(new CGPoint(), image.Size), cgimage);
                    }

            handle.Free();
        }
コード例 #30
0
        public async Task <byte[]> CropImage(byte[] image, FaceRectangle bound)
        {
            byte[]  croppedBytes = null;
            NSData  data         = NSData.FromArray(image);
            UIImage uiImage      = UIImage.LoadFromData(data);

            CGRect rect = new CGRect(bound.X, bound.Y, bound.Width, bound.Height);

            using (CGImage cr = uiImage.CGImage.WithImageInRect(rect))
            {
                UIImage cropped = UIImage.FromImage(cr);
                using (NSData imageData = cropped.AsJPEG())
                {
                    croppedBytes = new byte[imageData.Length];
                    System.Runtime.InteropServices.Marshal.Copy(imageData.Bytes, croppedBytes, 0, Convert.ToInt32(imageData.Length));
                }
            }

            return(croppedBytes);
        }
コード例 #31
0
        public void CALayer_ValuesTests()
        {
            CALayer layer   = new CALayer();
            CGRect  frame   = new CGRect(10, 10, 0, 0);
            CGImage image   = CGImage.ScreenImage(0, frame);
            NSImage NSImage = new NSImage();

            layer.Contents = image;
            CGImage arrayImage = layer.Contents;

            Assert.AreEqual(image.Handle, arrayImage.Handle);

            layer.SetContents(NSImage);
            NSImage arrayNSImage = layer.GetContentsAs <NSImage> ();

            Assert.AreEqual(NSImage.Handle, arrayNSImage.Handle);

            layer.SetContents(null);           // Should not throw
            layer.Contents = null;             // Should not throw
        }
コード例 #32
0
        private protected override bool TryOpenSourceSync(out _NativeImage image)
        {
            // Convert RGB colorspace.
            var bgraBuffer = _buffer.Data;
            var rgbaBuffer = new byte[bgraBuffer.Length];

            for (var i = 0; i < bgraBuffer.Length; i += 4)
            {
                rgbaBuffer[i + 3] = bgraBuffer[i + 3];                 // a
                rgbaBuffer[i + 0] = bgraBuffer[i + 2];                 // r
                rgbaBuffer[i + 1] = bgraBuffer[i + 1];                 // g
                rgbaBuffer[i + 2] = bgraBuffer[i + 0];                 // b
            }

            using (var dataProvider = new CGDataProvider(rgbaBuffer, 0, rgbaBuffer.Length))
                using (var colorSpace = CGColorSpace.CreateDeviceRGB())
                {
                    const int bitsPerComponent = 8;
                    const int bytesPerPixel    = 4;

                    var img = new CGImage(
                        PixelWidth,
                        PixelHeight,
                        bitsPerComponent: bitsPerComponent,
                        bitsPerPixel: bitsPerComponent * bytesPerPixel,
                        bytesPerRow: bytesPerPixel * PixelWidth,
                        colorSpace,
                        CGImageAlphaInfo.Last,
                        dataProvider,
                        decode: null,
                        shouldInterpolate: false,
                        CGColorRenderingIntent.Default);

#if __MACOS__
                    image = new _NativeImage(img, new CGSize(PixelWidth, PixelHeight));
#else
                    image = _NativeImage.FromImage(img);
#endif
                    return(true);
                }
        }
コード例 #33
0
        public static UIImage LoadGIFImage(string gifImage)
        {
            try
            {
                using (NSData imgData = NSData.FromFile(gifImage))
                    using (CGImageSource imgSource = CGImageSource.FromData(imgData))
                    {
                        NSString      gifKey      = new NSString(GIFKey);
                        NSString      gifDelayKey = new NSString(GIFDelayTimeKey);
                        List <double> frameDelays = new List <double>();

                        // Array that will hold each GIF frame.
                        UIImage[] frames = new UIImage[imgSource.ImageCount];

                        // Get all individual frames and their delay time.
                        for (int i = 0; i < imgSource.ImageCount; i++)
                        {
                            // Get the frame's property dictionary and the '{GIF}' dictionary from that.
                            using (NSDictionary frameProps = imgSource.CopyProperties(null, i))
                                using (NSMutableDictionary gifDict = (NSMutableDictionary)frameProps[gifKey])
                                {
                                    double frameDelay = ((NSNumber)gifDict[gifDelayKey]).DoubleValue;
                                    frameDelays.Add(frameDelay);
                                }                //end using

                            // Fill the array.
                            using (CGImage cgImage = imgSource.CreateImage(i, null))
                            {
                                frames[i] = UIImage.FromImage(cgImage);
                            }            //end using cgImage
                        }                //end for

                        // Create animated image.
                        return(UIImage.CreateAnimatedImage(frames, frameDelays.Sum()));
                    }            //end using
            } catch (Exception ex)
            {
                // Something went wrong!
                throw ex;
            }    //end try catch
        }        //end static UIImage LoadGifImage
コード例 #34
0
        UIImage CreateNonInterpolatedUIImageFormCIImage(CIImage image, nfloat size)
        {
            CGRect extent = image.Extent;
            float  scale  = (float)Math.Min(size / extent.Width, size / extent.Height);
            // 创建bitmap;
            int          width      = (int)(extent.Width * scale);
            int          height     = (int)(extent.Height * scale);
            CGColorSpace colorSpace = CGColorSpace.CreateDeviceGray();
//			var rawData = Marshal.AllocHGlobal(height * width * 4);
            CGBitmapContext bitmapRef   = new CGBitmapContext(null, width, height, 8, 0, colorSpace, CGImageAlphaInfo.None);
            CIContext       context     = CIContext.FromOptions(null);
            CGImage         bitmapImage = context.CreateCGImage(image, extent);

            bitmapRef.InterpolationQuality = CGInterpolationQuality.None;
            bitmapRef.ScaleCTM(scale, scale);
            bitmapRef.DrawImage(extent, bitmapImage);
            // 保存bitmap到图片
            CGImage scaledImage = bitmapRef.ToImage();

            return(new UIImage(scaledImage));
        }
コード例 #35
0
        public override void DidOutputSampleBuffer(AVCaptureOutput captureOutput, CMSampleBuffer sampleBuffer, AVCaptureConnection connection)
        {
            if (ready)
            {
                ready       = false;
                pixelBuffer = (CVPixelBuffer)sampleBuffer.GetImageBuffer();
                pixelBuffer.Lock(CVPixelBufferLock.None);

                width       = pixelBuffer.Width;
                height      = pixelBuffer.Height;
                bytesPerRow = pixelBuffer.BytesPerRow;

                context = new CGBitmapContext(pixelBuffer.BaseAddress, width, height, 8, bytesPerRow, colorSpace, CGImageAlphaInfo.PremultipliedFirst);
                cgImage = context.ToImage();
                uiImage = new UIImage(cgImage);
                pixelBuffer.Unlock(CVPixelBufferLock.None);
                pixelBuffer.Dispose();
                queue.DispatchAsync(ReadTask);
            }
            sampleBuffer.Dispose();
        }
コード例 #36
0
        CGImage NewCGImage(int width, int height, int bitsPerComponent, int bitsPerPixel, int bytesPerRow, CGColorSpace colorSpace, CGBitmapFlags bitmapFlags, CGDataProvider provider, nfloat[] decode, bool shouldInterpolate, CGColorRenderingIntent intent)
        {
            var image = new CGImage(width, height, bitsPerComponent, bitsPerPixel, bytesPerRow, colorSpace, bitmapFlags, dataProvider, decode, shouldInterpolate, intent);

            if (image == null)
            {
                var e = new ArgumentException("Failed to create CGImage");
                e.Data["width"]             = width;
                e.Data["height"]            = height;
                e.Data["bitsPerComponent"]  = bitsPerComponent;
                e.Data["bitsPerPixel"]      = bitsPerPixel;
                e.Data["bytesPerRow"]       = bytesPerRow;
                e.Data["colorSpace"]        = colorSpace;
                e.Data["bitmapFlags"]       = bitmapFlags;
                e.Data["dataProvider"]      = dataProvider;
                e.Data["decode"]            = decode;
                e.Data["shouldInterpolate"] = shouldInterpolate;
                e.Data["intent"]            = intent;
            }
            return(image);
        }
コード例 #37
0
        static XIR.Image RemoteRepresentation(CGImage image, nint width, nint height)
        {
            NSBitmapImageRep bitmap;

            if (width != image.Width || height != image.Height)
            {
                bitmap = new NSBitmapImageRep(image.Scale(new CGSize(width, height)));
            }
            else
            {
                bitmap = new NSBitmapImageRep(image);
            }

            var data = bitmap.RepresentationUsingTypeProperties(NSBitmapImageFileType.Png);

            return(new XIR.Image(
                       XIR.ImageFormat.Png,
                       data.ToArray(),
                       (int)width,
                       (int)height));
        }
コード例 #38
0
        public void CAKeyFrameAnimation_ValuesTests()
        {
            CAKeyFrameAnimation keyFrameAni = new CAKeyFrameAnimation();

            keyFrameAni.Values = new NSObject [] { new NSNumber(5) };
            Assert.AreEqual(1, keyFrameAni.Values.Length);
            NSNumber arrayNumber = (NSNumber)keyFrameAni.Values[0];

            Assert.AreEqual(5, arrayNumber.Int32Value);

            CGRect frame = new CGRect(10, 10, 10, 10);

            using (var provider = new CGDataProvider(new byte [(int)frame.Width * (int)frame.Height * 4])) {
                using (var image = new CGImage((int)frame.Width, (int)frame.Height, 8, 32, (int)frame.Width * 4, CGColorSpace.CreateDeviceRGB(), CGBitmapFlags.None, provider, null, false, CGColorRenderingIntent.Default)) {
                    keyFrameAni.SetValues(new CGImage [] { image, image });
                    Assert.AreEqual(2, keyFrameAni.Values.Length);
                    CGImage arrayImage = (CGImage)keyFrameAni.GetValuesAs <CGImage> ()[1];
                    Assert.AreEqual(image.Handle, arrayImage.Handle);
                }
            }
        }
コード例 #39
0
ファイル: FramePixelData.cs プロジェクト: Boerlam001/MonoGame
		public void Save (string path)
		{
			var extension = Path.GetExtension (path).ToLowerInvariant ();
			string uttype;
			switch (extension) {
			case ".png": uttype = "public.png"; break;
			case ".jpg":
			case ".jpeg": uttype = "public.jpeg"; break;
			default:
				throw new NotSupportedException(string.Format(
					"FramePixelData.Save cannot save images of type: {0}", extension));
			}

			//var documentsDir = Environment.GetFolderPath (Environment.SpecialFolder.Personal);

			var handle = GCHandle.Alloc(_data, GCHandleType.Pinned);
			try {
				var sizeOfColor = Marshal.SizeOf(typeof(Color));
				using (var dataProvider = new CGDataProvider(
					handle.AddrOfPinnedObject(), _data.Length * sizeOfColor, false))
				using (var colorSpace = CGColorSpace.CreateDeviceRGB())
				using (var image = new CGImage(
					Width, Height, 8, 32, Width * sizeOfColor, colorSpace,
					CGBitmapFlags.ByteOrder32Little | CGBitmapFlags.First,
					dataProvider, null, false, CGColorRenderingIntent.Default)) {

					//var fullPath = Path.Combine (documentsDir, path);
					Directory.CreateDirectory(Path.GetDirectoryName(path));

					var url = NSUrl.FromFilename (Path.GetFullPath(path));
					var destination = CGImageDestination.FromUrl(url, uttype, 1);
					destination.AddImage(image, null);
					if (!destination.Close())
						throw new Exception (string.Format (
							"Failed to write the image to '{0}'", path));
				}
			} finally {
				handle.Free ();
			}
		}
コード例 #40
0
ファイル: Icon.cs プロジェクト: emclient/mac-playground
        private bool LoadImageWithSize(Size size)
        {
            var  imageSource      = imageData.ImageSource;
            int  bestIndex        = (int)imageSource.ImageCount;     // intentionally out of range
            int  highestGoodIndex = -1;
            Size bestSize         = Size.Empty;

            for (int imageIndex = 0; imageIndex < imageSource.ImageCount; imageIndex++)
            {
                var properties = imageSource.GetPropertiesSafe(imageIndex);
                if (properties != null && properties.PixelWidth.Value <= size.Width && properties.PixelHeight.Value <= size.Height)
                {
                    if (properties.PixelWidth.Value > bestSize.Width || properties.PixelHeight.Value > bestSize.Height)
                    {
                        bestSize  = new Size(properties.PixelWidth.Value, properties.PixelHeight.Value);
                        bestIndex = imageIndex;
                    }
                    highestGoodIndex = imageIndex;
                }
                if (bestSize == size)
                {
                    break;
                }
            }

            if (bestIndex >= imageSource.ImageCount)
            {
                if (highestGoodIndex >= 0)
                {
                    bestIndex = highestGoodIndex;
                }
                else
                {
                    return(false);
                }
            }

            this.image = imageSource.CreateImage(bestIndex, null);
            return(this.image != null);
        }
コード例 #41
0
ファイル: CGContextRenderer.cs プロジェクト: detlevn/OsmSharp
        /// <summary>
        /// Draws an image on the target.
        /// </summary>
        /// <param name="target"></param>
        /// <param name="left"></param>
        /// <param name="top"></param>
        /// <param name="right"></param>
        /// <param name="bottom"></param>
        /// <param name="nativeImage"></param>
        /// <returns>The image.</returns>
        protected override void DrawImage(Target2DWrapper <CGContextWrapper> target, double left, double top, double right,
                                          double bottom, INativeImage nativeImage)
        {
            // get the native image.
            var iosNativeImage = (nativeImage as NativeImage);

            // get CGImage.
            CGImage image = iosNativeImage.Image;

            var bounds = new RectangleF2D(left, bottom, (left - right),
                                          (top - bottom));

            target.Target.CGContext.SetAllowsFontSubpixelQuantization(true);
            target.Target.CGContext.SetAllowsFontSmoothing(true);
            target.Target.CGContext.SetAllowsAntialiasing(true);
            target.Target.CGContext.SetAllowsSubpixelPositioning(true);
            target.Target.CGContext.SetShouldAntialias(true);

            PointF2D bottomLeft  = new PointF2D(this.Transform(bounds.BottomLeft[0], bounds.BottomLeft[1]));
            PointF2D bottomRight = new PointF2D(this.Transform(bounds.BottomRight[0], bounds.BottomRight[1]));
            PointF2D topLeft     = new PointF2D(this.Transform(bounds.TopLeft[0], bounds.TopLeft[1]));
            //PointF2D topRight = new PointF2D(this.Tranform (bounds.TopRight [0], bounds.TopRight [1]));

            RectangleF2D transformed = new RectangleF2D(bottomLeft, bottomLeft.Distance(bottomRight), bottomLeft.Distance(topLeft),
                                                        topLeft - bottomLeft);

            target.Target.CGContext.SaveState();
            target.Target.CGContext.TranslateCTM((float)transformed.BottomLeft[0], (float)transformed.BottomLeft[1]);
            target.Target.CGContext.RotateCTM(-(float)((Radian)transformed.Angle).Value);
            target.Target.CGContext.ScaleCTM(-1, 1);

            // build rectangle.
            _rectangle.X      = 0;
            _rectangle.Y      = 0;
            _rectangle.Width  = (float)transformed.Width;
            _rectangle.Height = (float)transformed.Height;
            target.Target.CGContext.DrawImage(_rectangle, image);

            target.Target.CGContext.RestoreState();
        }
コード例 #42
0
ファイル: ImageiOS.cs プロジェクト: tkcast/emgucv
 private void ConvertFromCGImage(CGImage cgImage)
 {
     //Don't do this, Xamarin.iOS won't be able to resolve: if (this is Image<Rgba, Byte>)
     if (typeof(TColor) == typeof(Rgba) && typeof(TDepth) == typeof(byte))
     {
         RectangleF rect = new RectangleF(PointF.Empty, new SizeF(cgImage.Width, cgImage.Height));
         using (CGColorSpace cspace = CGColorSpace.CreateDeviceRGB())
             using (CGBitmapContext context = new CGBitmapContext(
                        MIplImage.ImageData,
                        Width, Height,
                        8,
                        Width * 4,
                        cspace,
                        CGImageAlphaInfo.PremultipliedLast))
                 context.DrawImage(rect, cgImage);
     }
     else
     {
         using (Image <Rgba, Byte> tmp = new Image <Rgba, Byte>(cgImage))
             ConvertFrom(tmp);
     }
 }
コード例 #43
0
ファイル: GuiUtil.cs プロジェクト: xerohour/scsharp
        public static void RenderGlyphToContext(CGContext context, PointF position, Glyph g, Fnt font, byte[] palette, int offset)
        {
            byte[] buf = new byte[g.Width * g.Height * 4];
            int    i   = 0;

            for (int y = g.Height - 1; y >= 0; y--)
            {
                for (int x = g.Width - 1; x >= 0; x--)
                {
                    if (g.Bitmap[y, x] == 0)
                    {
                        buf [i + 0] = 0;
                    }
                    else if (g.Bitmap[y, x] == 1)
                    {
                        buf [i + 0] = 255;
                    }
                    else
                    {
                        buf [i + 0] = 128;
                    }

                    buf[i + 1] = palette[(g.Bitmap[y, x]) * 3 + offset + 0];
                    buf[i + 2] = palette[(g.Bitmap[y, x]) * 3 + offset + 1];
                    buf[i + 3] = palette[(g.Bitmap[y, x]) * 3 + offset + 2];

                    if (buf[i + 1] == 252 && buf[i + 2] == 0 && buf[i + 3] == 252)
                    {
                        buf[i + 0] = 0;
                    }

                    i += 4;
                }
            }

            CGImage glyphImage = CreateImage(buf, (ushort)g.Width, (ushort)g.Height, 32, g.Width * 4);

            context.DrawImage(new RectangleF(position, new SizeF(g.Width, g.Height)), glyphImage);
        }
コード例 #44
0
ファイル: ImageIO.cs プロジェクト: disenone/CrossStudy
        public byte[] ToPng(CImageByte img)
        {
            var provider = new CGDataProvider(img.Bytes, 0, (int)img.Length);
            int bitsPerComponent = 8;
            int components = (int)img.Channel;
            int bitsPerPixel = components * bitsPerComponent;
            int bytesPerRow = (int)img.Stride;

            // Tip:  When you create a bitmap graphics context, 
            // you’ll get the best performance if you make sure the data and bytesPerRow are 16-byte aligned.

            bool shouldInterpolate = false;
            var colorSpace = CGColorSpace.CreateDeviceRGB();
            var cgImage = new CGImage(
                (int)img.Width, (int)img.Height, bitsPerComponent, bitsPerPixel, bytesPerRow,
                 colorSpace, CGImageAlphaInfo.PremultipliedLast, provider,
                 null, shouldInterpolate, CGColorRenderingIntent.Default);

            var uimg = UIImage.FromImage(cgImage);

            Console.WriteLine("topng info: " + uimg.Size.ToString());

            return uimg.AsPNG().ToArray();
        }
コード例 #45
0
ファイル: ESTexture2D.cs プロジェクト: JoelCarter/MonoGame
 public ESTexture2D(CGImage cgImage, All filter)
 {
     InitWithCGImage(cgImage,filter);
 }
コード例 #46
0
ファイル: ESTexture2D.cs プロジェクト: JoelCarter/MonoGame
        private void InitWithCGImage(CGImage image, All filter)
        {
            int	width,height,i;
            CGContext context = null;
            IntPtr data;
            CGColorSpace colorSpace;
            IntPtr tempData;
            bool hasAlpha;
            CGImageAlphaInfo info;
            CGAffineTransform transform;
            Size imageSize;
            SurfaceFormat pixelFormat;
            bool sizeToFit = false;

            if(image == null)
            {
                throw new ArgumentException(" uimage is invalid! " );
            }

            info = image.AlphaInfo;
            hasAlpha = ((info == CGImageAlphaInfo.PremultipliedLast) || (info == CGImageAlphaInfo.PremultipliedFirst) || (info == CGImageAlphaInfo.Last) || (info == CGImageAlphaInfo.First) ? true : false);

            if (image.ColorSpace != null)
            {
                pixelFormat = SurfaceFormat.Color;
            }
            else
            {
                pixelFormat = SurfaceFormat.Alpha8;
            }

            imageSize = new Size(image.Width,image.Height);
            transform = CGAffineTransform.MakeIdentity();
            width = imageSize.Width;

            if((width != 1) && ((width & (width - 1))!=0)) {
                i = 1;
                while((sizeToFit ? 2 * i : i) < width)
                    i *= 2;
                width = i;
            }
            height = imageSize.Height;
            if((height != 1) && ((height & (height - 1))!=0)) {
                i = 1;
                while((sizeToFit ? 2 * i : i) < height)
                    i *= 2;
                height = i;
            }
            // TODO: kMaxTextureSize = 1024
            while((width > 1024) || (height > 1024))
            {
                width /= 2;
                height /= 2;
                transform = CGAffineTransform.MakeScale(0.5f,0.5f);
                imageSize.Width /= 2;
                imageSize.Height /= 2;
            }

            switch(pixelFormat)
            {
                case SurfaceFormat.Color:
                    colorSpace = CGColorSpace.CreateDeviceRGB();
                    data = Marshal.AllocHGlobal(height * width * 4);
                    context = new CGBitmapContext(data, width, height, 8, 4 * width, colorSpace,CGImageAlphaInfo.PremultipliedLast);
                    colorSpace.Dispose();
                    break;
                case SurfaceFormat.Alpha8:
                    data = Marshal.AllocHGlobal(height * width);
                    context = new CGBitmapContext(data, width, height, 8, width, null, CGImageAlphaInfo.Only);
                    break;
                default:
                    throw new NotSupportedException("Invalid pixel format");
            }

            context.ClearRect(new RectangleF(0,0,width,height));
             			context.TranslateCTM(0, height - imageSize.Height);

            if (!transform.IsIdentity)
            {
                context.ConcatCTM(transform);
            }

            context.DrawImage(new RectangleF(0, 0, image.Width, image.Height), image);

            //Convert "RRRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA" to "RRRRRGGGGGGBBBBB"
            /*
            if(pixelFormat == SurfaceFormat.Rgb32) {
                tempData = Marshal.AllocHGlobal(height * width * 2);

                int d32;
                short d16;
                int inPixel32Count=0,outPixel16Count=0;
                for(i = 0; i < width * height; ++i, inPixel32Count+=sizeof(int))
                {
                    d32 = Marshal.ReadInt32(data,inPixel32Count);
                    short R = (short)((((d32 >> 0) & 0xFF) >> 3) << 11);
                    short G = (short)((((d32 >> 8) & 0xFF) >> 2) << 5);
                    short B = (short)((((d32 >> 16) & 0xFF) >> 3) << 0);
                    d16 = (short)  (R | G | B);
                    Marshal.WriteInt16(tempData,outPixel16Count,d16);
                    outPixel16Count += sizeof(short);
                }
                Marshal.FreeHGlobal(data);
                data = tempData;
            }
            */

            InitWithData(data,pixelFormat,width,height,imageSize, filter);

            context.Dispose();
            Marshal.FreeHGlobal (data);
        }
コード例 #47
0
        internal CGBitmapContext GetRenderableContext()
        {
            if (cachedContext != null && cachedContext.Handle != IntPtr.Zero)
                return cachedContext;

            var format = GetBestSupportedFormat (pixelFormat);
            var bitmapContext = CreateCompatibleBitmapContext ((int)NativeCGImage.Width, (int)NativeCGImage.Height, format);

            bitmapContext.DrawImage (new CGRect (0, 0, NativeCGImage.Width, NativeCGImage.Height), NativeCGImage);

            int size = (int)(bitmapContext.BytesPerRow * bitmapContext.Height);
            var provider = new CGDataProvider (bitmapContext.Data, size, true);

            CGColorSpace colorSpace = CGColorSpace.CreateDeviceRGB();
            NativeCGImage = new CGImage ((int)bitmapContext.Width, (int)bitmapContext.Height, (int)bitmapContext.BitsPerComponent,
                                         (int)bitmapContext.BitsPerPixel, (int)bitmapContext.BytesPerRow,
                                         colorSpace,
                                         bitmapContext.AlphaInfo,
                                         provider, null, true, CGColorRenderingIntent.Default);
            colorSpace.Dispose ();
            cachedContext = bitmapContext;

            return cachedContext;
        }
コード例 #48
0
ファイル: ApplePlatform.cs プロジェクト: nakijun/NGraphics
 public CGImageImage(CGImage image, double scale)
 {
     if (image == null)
         throw new ArgumentNullException ("image");
     this.image = image;
     this.scale = scale;
     this.size = new Size (image.Width / scale, image.Height / scale);
 }
コード例 #49
0
        internal void RotateFlip(RotateFlipType rotateFlipType)
        {
            CGAffineTransform rotateFlip = CGAffineTransform.MakeIdentity();

            int width, height;
            width = (int)NativeCGImage.Width;
            height = (int)NativeCGImage.Height;

            switch (rotateFlipType)
            {
                //			case RotateFlipType.RotateNoneFlipNone:
                //			//case RotateFlipType.Rotate180FlipXY:
                //				rotateFlip = GeomUtilities.CreateRotateFlipTransform (b.Width, b.Height, 0, false, false);
                //				break;
                case RotateFlipType.Rotate90FlipNone:
                //case RotateFlipType.Rotate270FlipXY:
                rotateFlip = GeomUtilities.CreateRotateFlipTransform (ref width, ref height, 90, false, false);
                break;
                case RotateFlipType.Rotate180FlipNone:
                //case RotateFlipType.RotateNoneFlipXY:
                rotateFlip = GeomUtilities.CreateRotateFlipTransform (ref width, ref height, 0, true, true);
                break;
                case RotateFlipType.Rotate270FlipNone:
                //case RotateFlipType.Rotate90FlipXY:
                rotateFlip = GeomUtilities.CreateRotateFlipTransform (ref width, ref height, 270, false, false);
                break;
                case RotateFlipType.RotateNoneFlipX:
                //case RotateFlipType.Rotate180FlipY:
                rotateFlip = GeomUtilities.CreateRotateFlipTransform (ref width, ref height, 0, true, false);
                break;
                case RotateFlipType.Rotate90FlipX:
                //case RotateFlipType.Rotate270FlipY:
                rotateFlip = GeomUtilities.CreateRotateFlipTransform (ref width, ref height, 90, true, false);
                break;
                case RotateFlipType.Rotate180FlipX:
                //case RotateFlipType.RotateNoneFlipY:
                rotateFlip = GeomUtilities.CreateRotateFlipTransform (ref width, ref height, 0, false, true);
                break;
                case RotateFlipType.Rotate270FlipX:
                //case RotateFlipType.Rotate90FlipY:
                rotateFlip = GeomUtilities.CreateRotateFlipTransform (ref width, ref height, 270, true, false);
                break;
            }

            var format = GetBestSupportedFormat (pixelFormat);
            var bitmapContext = CreateCompatibleBitmapContext (width, height, format);

            bitmapContext.ConcatCTM (rotateFlip);

            bitmapContext.DrawImage (new CGRect (0, 0, NativeCGImage.Width, NativeCGImage.Height), NativeCGImage);

            int size = (int)(bitmapContext.BytesPerRow * bitmapContext.Height);
            var provider = new CGDataProvider (bitmapContext.Data, size, true);

            // If the width or height is not the seme we need to switch the dpiHeight and dpiWidth
            // We should be able to get around this with set resolution later.
            if (NativeCGImage.Width != width || NativeCGImage.Height != height)
            {
                var temp = dpiWidth;
                dpiHeight = dpiWidth;
                dpiWidth = temp;
            }

            NativeCGImage = new CGImage ((int)bitmapContext.Width, (int)bitmapContext.Height, (int)bitmapContext.BitsPerComponent,
                                         (int)bitmapContext.BitsPerPixel, (int)bitmapContext.BytesPerRow,
                                         bitmapContext.ColorSpace,
                                         bitmapContext.AlphaInfo,
                                         provider, null, true, CGColorRenderingIntent.Default);

            physicalDimension.Width = (float)width;
            physicalDimension.Height = (float)height;

            physicalSize = new SizeF (physicalDimension.Width, physicalDimension.Height);
            physicalSize.Width *= ConversionHelpers.MS_DPI / dpiWidth;
            physicalSize.Height *= ConversionHelpers.MS_DPI / dpiHeight;

            // In windows the RawFormat is changed to MemoryBmp to show that the image has changed.
            rawFormat = ImageFormat.MemoryBmp;

            // Set our transform for this image for the new height
            imageTransform = new CGAffineTransform(1, 0, 0, -1, 0, height);
        }
コード例 #50
0
        public Bitmap(int width, int height, PixelFormat format)
        {
            int bitsPerComponent, bytesPerRow;
            CGColorSpace colorSpace;
            CGBitmapFlags bitmapInfo;
            bool premultiplied = false;
            int bitsPerPixel = 0;

            switch (format){
            case PixelFormat.Format32bppPArgb:
                premultiplied = true;
                colorSpace = CGColorSpace.CreateDeviceRGB ();
                bitsPerComponent = 8;
                bitsPerPixel = 32;
                bitmapInfo = CGBitmapFlags.PremultipliedFirst;
                break;
            case PixelFormat.Format32bppArgb:
                colorSpace = CGColorSpace.CreateDeviceRGB ();
                bitsPerComponent = 8;
                bitsPerPixel = 32;
                bitmapInfo = CGBitmapFlags.PremultipliedFirst;
                break;
            case PixelFormat.Format32bppRgb:
                colorSpace = CGColorSpace.CreateDeviceRGB ();
                bitsPerComponent = 8;
                bitsPerPixel = 32;
                bitmapInfo = CGBitmapFlags.None;
                break;
            default:
                throw new Exception ("Format not supported: " + format);
            }
            bytesPerRow = width * bitsPerPixel/bitsPerComponent;
            int size = bytesPerRow * height;
            bitmapBlock = Marshal.AllocHGlobal (size);

            var provider = new CGDataProvider (bitmapBlock, size, true);
            NativeCGImage = new CGImage (width, height, bitsPerComponent, bitsPerPixel, bytesPerRow, colorSpace, bitmapInfo, provider, null, false, CGColorRenderingIntent.Default);
        }
コード例 #51
0
 public CustomImageView (IntPtr p) : base(p)
 {
     _monkeyImage = UIImage.FromFile ("monkey.jpg").CGImage;
 }
コード例 #52
0
ファイル: CIImage.cs プロジェクト: roblillack/maccore
        public static CIImage FromCGImage(CGImage image, CGColorSpace colorSpace)
        {
            if (colorSpace == null)
                throw new ArgumentNullException ("colorSpace");

            using (var arr = NSArray.FromIntPtrs (new IntPtr [] { colorSpace.Handle })){
                using (var keys = NSArray.FromIntPtrs (new IntPtr [] { CIImageColorSpace.Handle } )){
                    using (var dict = NSDictionary.FromObjectsAndKeysInternal (arr, keys)){
                        return FromCGImage (image, dict);
                    }
                }
            }
        }
コード例 #53
0
ファイル: SMPageControl.cs プロジェクト: skela/SMPageControl
        public void SetPageIndicatorMaskImage(UIImage _pageIndicatorMaskImage)
        {
            if (pageIndicatorMaskImage!=null && pageIndicatorMaskImage.Equals(pageIndicatorMaskImage))
            {
                return;
            }

            pageIndicatorMaskImage = _pageIndicatorMaskImage;

            /*
            if (pageImageMask)
            {
                CGImageRelease(pageImageMask);
            }*/

            pageImageMask = CreateMaskForImage (pageIndicatorMaskImage);

            UpdateMeasuredIndicatorSizes ();
            SetNeedsDisplay ();
        }
コード例 #54
0
ファイル: Image.cs プロジェクト: CBrauer/monotouch-samples
		static UIImage Resize(CGImage original, nfloat scale, UIImageOrientation orientation, CGSize newSize)
		{
			UIGraphics.BeginImageContext(newSize);

			var rect = new CGRect (CGPoint.Empty, newSize);
			UIImage.FromImage (original, scale, orientation).Draw (rect);
			UIImage resized = UIGraphics.GetImageFromCurrentImageContext ();

			UIGraphics.EndImageContext ();

			return resized;
		}
コード例 #55
0
 public async Task<bool> Recognise (CGImage image)
 {
     using (var ciImage = new CIImage (image)) {
         return await Recognise (ciImage);
     }
 }
コード例 #56
0
 protected override void Dispose(bool disposing)
 {
     if (disposing){
         if (NativeCGImage != null){
             NativeCGImage.Dispose ();
             NativeCGImage = null;
         }
         bitmapBlock = IntPtr.Zero;
     }
     base.Dispose (disposing);
 }
コード例 #57
0
        public Bitmap(int width, int height, PixelFormat format)
        {
            imageTransform = new CGAffineTransform(1, 0, 0, -1, 0, height);

            int bitsPerComponent, bytesPerRow;
            CGColorSpace colorSpace;
            CGBitmapFlags bitmapInfo;
            bool premultiplied = false;
            int bitsPerPixel = 0;

            pixelFormat = format;

            // Don't forget to set the Image width and height for size.
            imageSize.Width = width;
            imageSize.Height = height;

            switch (format){
            case PixelFormat.Format32bppPArgb:
            case PixelFormat.DontCare:
                premultiplied = true;
                colorSpace = CGColorSpace.CreateDeviceRGB ();
                bitsPerComponent = 8;
                bitsPerPixel = 32;
                bitmapInfo = CGBitmapFlags.PremultipliedFirst;
                break;
            case PixelFormat.Format32bppArgb:
                colorSpace = CGColorSpace.CreateDeviceRGB ();
                bitsPerComponent = 8;
                bitsPerPixel = 32;
                bitmapInfo = CGBitmapFlags.PremultipliedFirst;
                break;
            case PixelFormat.Format32bppRgb:
                colorSpace = CGColorSpace.CreateDeviceRGB ();
                bitsPerComponent = 8;
                bitsPerPixel = 32;
                bitmapInfo = CGBitmapFlags.NoneSkipLast;
                break;
            case PixelFormat.Format24bppRgb:
                colorSpace = CGColorSpace.CreateDeviceRGB ();
                bitsPerComponent = 8;
                bitsPerPixel = 32;
                bitmapInfo = CGBitmapFlags.NoneSkipLast;
                break;
            default:
                throw new Exception ("Format not supported: " + format);
            }
            bytesPerRow = width * bitsPerPixel/bitsPerComponent;
            int size = bytesPerRow * height;

            bitmapBlock = Marshal.AllocHGlobal (size);
            var bitmap = new CGBitmapContext (bitmapBlock,
                                          width, height,
                                          bitsPerComponent,
                                          bytesPerRow,
                                          colorSpace,
                                          bitmapInfo);
            // This works for now but we need to look into initializing the memory area itself
            // TODO: Look at what we should do if the image does not have alpha channel
            bitmap.ClearRect (new CGRect (0,0,width,height));

            var provider = new CGDataProvider (bitmapBlock, size, true);
            NativeCGImage = new CGImage (width, height, bitsPerComponent, bitsPerPixel, bytesPerRow, colorSpace, bitmapInfo, provider, null, false, CGColorRenderingIntent.Default);

            dpiWidth = dpiHeight = ConversionHelpers.MS_DPI;
            physicalDimension.Width = width;
            physicalDimension.Height = height;

            // The physical size may be off on certain implementations.  For instance the dpiWidth and dpiHeight
            // are read using integers in core graphics but in windows it is a float.
            // For example:
            // coregraphics dpiWidth = 24 as integer
            // windows dpiWidth = 24.999935 as float
            // this gives a few pixels difference when calculating the physical size.
            // 256 * 96 / 24 = 1024
            // 256 * 96 / 24.999935 = 983.04
            //
            // https://bugzilla.xamarin.com/show_bug.cgi?id=14365
            // PR: https://github.com/mono/maccore/pull/57
            //

            physicalSize = new SizeF (physicalDimension.Width, physicalDimension.Height);
            physicalSize.Width *= ConversionHelpers.MS_DPI / dpiWidth;
            physicalSize.Height *= ConversionHelpers.MS_DPI / dpiHeight;

            rawFormat = ImageFormat.MemoryBmp;
            pixelFormat = format;
        }
コード例 #58
0
		public UIKitImage (CGImage image)
		{
			Image = image;
		}
コード例 #59
0
        public UIImage Capture()
        {
            // This is from: https://developer.apple.com/library/ios/#qa/qa2010/qa1704.html

            int backingWidth, backingHeight;

            // Bind the color renderbuffer used to render the OpenGL ES view
            // If your application only creates a single color renderbuffer which is already bound at this point,
            // this call is redundant, but it is needed if you're dealing with multiple renderbuffers.
            // Note, replace "_colorRenderbuffer" with the actual name of the renderbuffer object defined in your class.
            gl.BindRenderbuffer (All.RenderbufferOes, Renderbuffer);

            // Get the size of the backing CAEAGLLayer
            gl.GetRenderbufferParameter (All.RenderbufferOes, All.RenderbufferWidthOes, out backingWidth);
            gl.GetRenderbufferParameter (All.RenderbufferOes, All.RenderbufferHeightOes, out backingHeight);

            int width = backingWidth, height = backingHeight;
            int dataLength = width * height * 4;
            byte[] data = new byte [dataLength];

            // Read pixel data from the framebuffer
            gl.PixelStore (All.PackAlignment, 4);
            gl.ReadPixels (0, 0, width, height, All.Rgba, All.UnsignedByte, data);

            // Create a CGImage with the pixel data
            // If your OpenGL ES content is opaque, use kCGImageAlphaNoneSkipLast to ignore the alpha channel
            // otherwise, use kCGImageAlphaPremultipliedLast
            using (var data_provider = new CGDataProvider (data, 0, data.Length)) {
                using (var colorspace = CGColorSpace.CreateDeviceRGB ()) {
                    using (var iref = new CGImage (width, height, 8, 32, width * 4, colorspace,
                                    (CGImageAlphaInfo) ((int) CGBitmapFlags.ByteOrder32Big | (int) CGImageAlphaInfo.PremultipliedLast),
                                    data_provider, null, true, CGColorRenderingIntent.Default)) {

                        // OpenGL ES measures data in PIXELS
                        // Create a graphics context with the target size measured in POINTS
                        int widthInPoints, heightInPoints;
                        float scale = ContentScaleFactor;
                        widthInPoints = (int) (width / scale);
                        heightInPoints = (int) (height / scale);
                        UIGraphics.BeginImageContextWithOptions (new System.Drawing.SizeF (widthInPoints, heightInPoints), false, scale);

                        try {
                            var cgcontext = UIGraphics.GetCurrentContext ();

                            // UIKit coordinate system is upside down to GL/Quartz coordinate system
                            // Flip the CGImage by rendering it to the flipped bitmap context
                            // The size of the destination area is measured in POINTS
                            cgcontext.SetBlendMode (CGBlendMode.Copy);
                            cgcontext.DrawImage (new System.Drawing.RectangleF (0, 0, widthInPoints, heightInPoints), iref);

                            // Retrieve the UIImage from the current context
                            var image = UIGraphics.GetImageFromCurrentImageContext ();

                            return image;
                        } finally {
                            UIGraphics.EndImageContext ();
                        }
                    }
                }
            }
        }
コード例 #60
0
        private void DrawImage(RectangleF rect, CGImage image, CGAffineTransform transform)
        {
            var trans = transform;
            // Do our translation on the image transform
            trans.Translate (rect.X, rect.Height - image.Height + rect.Y);

            // The translation is already taken care of in the transform
            rect.Y = 0;
            rect.X = 0;

            // Apply our transform to the context
            context.ConcatCTM (trans);

            // we are getting an error somewhere and not sure where
            // I think the image bitmapBlock is being corrupted somewhere
            try {
                context.DrawImage (rect.ToCGRect (), image);
            }
            catch (Exception exc)
            {
                Console.WriteLine(exc.Message);
            }

            // Now we revert our image transform from the context
            var revert = CGAffineTransform.CGAffineTransformInvert (trans);
            context.ConcatCTM (revert);
        }