/// <exception cref="Couchbase.Lite.CouchbaseLiteException"></exception>
 public static Couchbase.Lite.Document CreateTask(Database database, string title, 
     Bitmap image, string listId)
 {
     SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
         );
     Calendar calendar = GregorianCalendar.GetInstance();
     string currentTimeString = dateFormatter.Format(calendar.GetTime());
     IDictionary<string, object> properties = new Dictionary<string, object>();
     properties.Put("type", DocType);
     properties.Put("title", title);
     properties.Put("checked", false);
     properties.Put("created_at", currentTimeString);
     properties.Put("list_id", listId);
     Couchbase.Lite.Document document = database.CreateDocument();
     UnsavedRevision revision = document.CreateRevision();
     revision.SetUserProperties(properties);
     if (image != null)
     {
         ByteArrayOutputStream @out = new ByteArrayOutputStream();
         image.Compress(Bitmap.CompressFormat.Jpeg, 50, @out);
         ByteArrayInputStream @in = new ByteArrayInputStream(@out.ToByteArray());
         revision.SetAttachment("image", "image/jpg", @in);
     }
     revision.Save();
     return document;
 }
Example #2
0
        /// <summary>
        /// Copies the pixel data to bitmap, data assumed to be in ARGB format so it will be trasformed to the internal Android ABGR format that bitmaps use while copying.
        /// </summary>
        /// <param name="targetBitmap">The target bitmap.</param>
        /// <param name="data">The data.</param>
        /// <param name="stride">The stride, bitmap width in pixels.</param>
        public static void CopyPixelDataToBitmap(Bitmap targetBitmap, int[] data, int stride)
        {
            if (targetBitmap != null)
            {
                IntPtr ptr = targetBitmap.LockPixels();

                unchecked
                {
                    int value;

                    int[] strideArray = new int[stride];

                    for (int i = 0; i < data.Length; i += stride)
                    {
                        for (int j = 0, k = i; j < stride; ++j, ++k)
                        {
                            value = data[k];

                            strideArray[j] =
                                (int)
                                ((0xFF000000) | ((value & 0xFF) << 16) | (value & 0x0000FF00) | ((value >> 16) & 0xFF));
                        }

                        Marshal.Copy(strideArray, 0, ptr + (i << 2), stride);
                    }
                }
                targetBitmap.UnlockPixels();
            }
        }
        public void LoadFromResource(string assemblyName,MvxResourcePath resourcePath)
        {
            var resourceName = resourcePath.GetResourcePath (".",true);
            var strm = Assembly.Load (new AssemblyName(assemblyName)).GetManifestResourceStream(resourceName);

            bitmap = BitmapFactory.DecodeStream (strm);
        }
		public AchievementElement(string caption, string description, int percentageComplete, Bitmap achievementImage)
            : base(caption, (int)DroidResources.ElementLayout.dialog_achievements)
        {
			Description = description;
			PercentageComplete = percentageComplete;
			AchievementImage = achievementImage;
        }
Example #5
0
 public AndroidGraphics(AssetManager am, Bitmap bm)
 {
     this.assets = am;
     this.frameBuffer = bm;
     this.canvas = new Canvas (frameBuffer);
     this.paint = new Paint ();
 }
Example #6
0
		protected override void OnSizeChanged(int w, int h, int oldw, int oldh)
		{
			base.OnSizeChanged(w, h, oldw, oldh);

			CanvasBitmap = Bitmap.CreateBitmap(w, h, Bitmap.Config.Argb8888);
			DrawCanvas = new Canvas(CanvasBitmap);
		}
Example #7
0
        public static bool PutBitmapToCacheByUrl (string url, Bitmap bitmap, Context ctx)
        {
            var imagePath = GetCachePathForUrl (url, "UserImages", ctx);

            try {
                Directory.CreateDirectory (FilePath.GetDirectoryName (imagePath));
                using (var fileStream = new FileStream (imagePath + ".png", FileMode.Create)) {
                    bitmap.Compress (Bitmap.CompressFormat.Png, 90, fileStream);
                }
                return true;
            } catch (IOException ex) {
                var log = ServiceContainer.Resolve<ILogger> ();
                if (ex.Message.StartsWith ("Sharing violation on")) {
                    // Treat FAT filesystem related failure as expected behaviour
                    log.Info (LogTag, ex, "Failed to save bitmap to cache.");
                } else {
                    log.Warning (LogTag, ex, "Failed to save bitmap to cache.");
                }
                return false;
            } catch (Exception ex) {
                var log = ServiceContainer.Resolve<ILogger> ();
                log.Warning (LogTag, ex, "Failed to save bitmap to cache.");
                return false;
            }
        }
        /// <summary>
        /// Saves the specified render target as an image with the specified format.
        /// </summary>
        /// <param name="renderTarget">The render target to save.</param>
        /// <param name="stream">The stream to which to save the render target data.</param>
        /// <param name="format">The format with which to save the image.</param>
        private void Save(RenderTarget2D renderTarget, Stream stream, Bitmap.CompressFormat format)
        {
            var data = new Color[renderTarget.Width * renderTarget.Height];
            renderTarget.GetData(data);

            Save(data, renderTarget.Width, renderTarget.Height, stream, format);
        }
        static Bitmap GetCroppedBitmap (Bitmap bmp, int radius)
        {
            Bitmap sbmp;
            if (bmp.Width != radius || bmp.Height != radius)
                sbmp = Bitmap.CreateScaledBitmap (bmp, radius, radius, false);
            else
                sbmp = bmp;
            var output = Bitmap.CreateBitmap (sbmp.Width,
                             sbmp.Height, Bitmap.Config.Argb8888);
            var canvas = new Canvas (output);

            var paint = new Paint ();
            var rect = new Rect (0, 0, sbmp.Width, sbmp.Height);

            paint.AntiAlias = true;
            paint.FilterBitmap = true;
            paint.Dither = true;
            canvas.DrawARGB (0, 0, 0, 0);
            paint.Color = Color.ParseColor ("#BAB399");
            canvas.DrawCircle (sbmp.Width / 2 + 0.7f, sbmp.Height / 2 + 0.7f,
                sbmp.Width / 2 + 0.1f, paint);
            paint.SetXfermode (new PorterDuffXfermode (PorterDuff.Mode.SrcIn));
            canvas.DrawBitmap (sbmp, rect, rect, paint);

            return output;
        }
		protected override Bitmap Transform(IBitmapPool bitmapPool, Bitmap source, int outWidth, int outHeight)
		{
			int size = Math.Min(source.Width, source.Height);

			int width = (source.Width - size) / 2;
			int height = (source.Height - size) / 2;

			Bitmap squaredBitmap = Bitmap.CreateBitmap(source, width, height, size, size);
			if (squaredBitmap != source)
			{
				source.Recycle();
			}

			Bitmap bitmap = Bitmap.CreateBitmap(size, size, Bitmap.Config.Argb8888);

			Canvas canvas = new Canvas(bitmap);
			Paint paint = new Paint();
			BitmapShader shader = new BitmapShader(squaredBitmap, BitmapShader.TileMode.Clamp,
					BitmapShader.TileMode.Clamp);
			paint.SetShader(shader);
			paint.AntiAlias = true;

			float r = size / 2f;
			canvas.DrawCircle(r, r, r, paint);

			squaredBitmap.Recycle();

			return BitmapResource.Obtain(bitmap, bitmapPool).Get();
		}
        /**
	     * This will generate a bitmap with the pattern
	     * as big as the rectangle we were allow to draw on.
	     * We do this to chache the bitmap so we don't need to
	     * recreate it each time draw() is called since it
	     * takes a few milliseconds.
	     */
        private void GeneratePatternBitmap()
        {

            if (Bounds.Width() <= 0 || Bounds.Height() <= 0)
            {
                return;
            }

            _bitmap = Bitmap.CreateBitmap(Bounds.Width(), Bounds.Height(), Bitmap.Config.Argb8888);

            using (var canvas = new Canvas(_bitmap))
            {
                var r = new Rect();
                var verticalStartWhite = true;
                for (var i = 0; i <= _numRectanglesVertical; i++)
                {
                    var isWhite = verticalStartWhite;
                    for (var j = 0; j <= _numRectanglesHorizontal; j++)
                    {

                        r.Top = i * _rectangleSize;
                        r.Left = j * _rectangleSize;
                        r.Bottom = r.Top + _rectangleSize;
                        r.Right = r.Left + _rectangleSize;

                        canvas.DrawRect(r, isWhite ? _paintWhite : _paintGray);

                        isWhite = !isWhite;
                    }

                    verticalStartWhite = !verticalStartWhite;
                }
            }
        }
        private static void SaveFromMemory(PixelBuffer[] pixelBuffers, int count, ImageDescription description, Stream imageStream, Bitmap.CompressFormat imageFormat)
        {
            var colors = pixelBuffers[0].GetPixels<int>();

            using (var bitmap = Bitmap.CreateBitmap(description.Width, description.Height, Bitmap.Config.Argb8888))
            {
                var pixelData = bitmap.LockPixels();
                var sizeToCopy = colors.Length * sizeof(int);

                unsafe
                {
                    fixed (int* pSrc = colors)
                    {
                        // Copy the memory
                        if (description.Format == PixelFormat.R8G8B8A8_UNorm || description.Format == PixelFormat.R8G8B8A8_UNorm_SRgb)
                        {
                            CopyMemoryBGRA(pixelData, (IntPtr)pSrc, sizeToCopy);
                        }
                        else if (description.Format == PixelFormat.B8G8R8A8_UNorm || description.Format == PixelFormat.B8G8R8A8_UNorm_SRgb)
                        {
                            Utilities.CopyMemory(pixelData, (IntPtr)pSrc, sizeToCopy);
                        }
                        else
                        {
                            throw new NotSupportedException(string.Format("Pixel format [{0}] is not supported", description.Format));
                        }
                    }
                }

                bitmap.UnlockPixels();
                bitmap.Compress(imageFormat, 100, imageStream);
            }
        }
		public static Bitmap getRoundedCroppedBitmap(Bitmap bitmap, int radius) {
			Bitmap finalBitmap;
			if (bitmap.Width != radius || bitmap.Height!= radius)
				finalBitmap = Bitmap.CreateScaledBitmap(bitmap, radius, radius,
					false);
			else
				finalBitmap = bitmap;
			Bitmap output = Bitmap.CreateBitmap(finalBitmap.Width,
				finalBitmap.Height, Bitmap.Config.Argb8888);
			Canvas canvas = new Canvas(output);

			 Paint paint = new Paint();
			Rect rect = new Rect(0, 0, finalBitmap.Width,
				finalBitmap.Height);

			paint.AntiAlias=true;
			paint.FilterBitmap=true;
			paint.Dither=true;
			canvas.DrawARGB(0, 0, 0, 0);
			paint.Color=Color.ParseColor("#BAB399");
			canvas.DrawCircle(finalBitmap.Width / 2 + 0.7f,
				finalBitmap.Height / 2 + 0.7f,
				finalBitmap.Width / 2 + 0.1f, paint);
			paint.SetXfermode(new PorterDuffXfermode(PorterDuff.Mode.SrcIn));
			canvas.DrawBitmap(finalBitmap, rect, rect, paint);

			return output;
		}	
Example #14
0
 public SelfDisposingBitmapDrawable AddOrUpdate(string key, Bitmap bmp, TimeSpan duration)
 {
     diskCache.AddOrUpdate (key, bmp, duration);
     var drawable = CreateCacheableDrawable (bmp);
     memCache.Add (new Uri (key), drawable);
     return drawable;
 }
		public static Bitmap ToRounded(Bitmap source, float rad, double cropWidthRatio, double cropHeightRatio, double borderSize, string borderHexColor)
		{
			double sourceWidth = source.Width;
			double sourceHeight = source.Height;

			double desiredWidth = sourceWidth;
			double desiredHeight = sourceHeight;

			double desiredRatio = cropWidthRatio / cropHeightRatio;
			double currentRatio = sourceWidth / sourceHeight;

			if (currentRatio > desiredRatio)
				desiredWidth = (cropWidthRatio * sourceHeight / cropHeightRatio);
			else if (currentRatio < desiredRatio)
				desiredHeight = (cropHeightRatio * sourceWidth / cropWidthRatio);

			float cropX = (float)((sourceWidth - desiredWidth) / 2d);
			float cropY = (float)((sourceHeight - desiredHeight) / 2d);

			if (rad == 0)
				rad = (float)(Math.Min(desiredWidth, desiredHeight) / 2d);
			else
				rad = (float)(rad * (desiredWidth + desiredHeight) / 2d / 500d);

			Bitmap bitmap = Bitmap.CreateBitmap((int)desiredWidth, (int)desiredHeight, Bitmap.Config.Argb8888);

			using (Canvas canvas = new Canvas(bitmap))
			using (Paint paint = new Paint())
			using (BitmapShader shader = new BitmapShader(source, Shader.TileMode.Clamp, Shader.TileMode.Clamp))
			using (Matrix matrix = new Matrix())
			{
				if (cropX != 0 || cropY != 0)
				{
					matrix.SetTranslate(-cropX, -cropY);
					shader.SetLocalMatrix(matrix);
				}

				paint.SetShader(shader);
				paint.AntiAlias = true;

				RectF rectF = new RectF(0f, 0f, (float)desiredWidth, (float)desiredHeight);
				canvas.DrawRoundRect(rectF, rad, rad, paint);

				if (borderSize > 0d) 
				{
					borderSize = (borderSize * (desiredWidth + desiredHeight) / 2d / 500d);
					paint.Color = borderHexColor.ToColor(); ;
					paint.SetStyle(Paint.Style.Stroke);
					paint.StrokeWidth = (float)borderSize;
					paint.SetShader(null);

					RectF borderRectF = new RectF((float)(0d + borderSize/2d), (float)(0d + borderSize/2d), 
						(float)(desiredWidth - borderSize/2d), (float)(desiredHeight - borderSize/2d));

					canvas.DrawRoundRect(borderRectF, rad, rad, paint);
				}

				return bitmap;				
			}
		}
Example #16
0
        public async Task<Bitmap> GetResizedBitmapAsync(string path, int width, int height)
        {
            if (_originalBitmap != null)
            {
                return _originalBitmap;
            }

            #region Get some some information about the bitmap so we can resize it
            BitmapFactory.Options options = new BitmapFactory.Options
                                            {
                                                InJustDecodeBounds = true
                                            };

            using (Stream stream = _context.Assets.Open(path))
            {
                await BitmapFactory.DecodeStreamAsync(stream);
            }
            await BitmapFactory.DecodeFileAsync(path, options);
            #endregion

            // Calculate the factor by which we should reduce the image by
            options.InSampleSize = CalculateInSampleSize(options, width, height);

            #region Go and load the image and resize it at the same time.
            options.InJustDecodeBounds = false;

            using (Stream inputSteam = _context.Assets.Open(path))
            {
                _originalBitmap = await BitmapFactory.DecodeStreamAsync(inputSteam);
            }
            #endregion

            return _originalBitmap;
        }
		public void putBitmap (string key, Bitmap bitmap)
		{
			Put (key, bitmap);

			// An entry has been added, so invalidate the snapshot
			mLastSnapshot = null;
		}
Example #18
0
        public override bool OnTouchEvent(MotionEvent e)
        {
            _Paint = new Paint ();
            _Paint.Color = new Android.Graphics.Color (255, 0, 0);
            _Paint.StrokeWidth = 20;
            _Paint.StrokeCap = Paint.Cap.Round;
            var imageView = FindViewById<ImageView> (Resource.Id.myImageView);
            Bitmap immutableBitmap = MediaStore.Images.Media.GetBitmap(this.ContentResolver, imageUri);
            _Bmp = immutableBitmap.Copy(Bitmap.Config.Argb8888, true);
            _Canvas = new Canvas(_Bmp);
            imageView.SetImageBitmap (_Bmp);
                switch (e.Action)
                {

                default:
                {
                    _StartPt.X=e.RawX;
                    _StartPt.Y=e.RawY;
                    Console.WriteLine ("inside default:{0}","default");
                    DrawPoint (_Canvas);
                    break;
                }
                }

            return true;
        }
Example #19
0
        /// <summary>
        /// Saves the specified surface as an image with the specified format.
        /// </summary>
        /// <param name="renderTarget">The surface to save.</param>
        /// <param name="stream">The stream to which to save the surface data.</param>
        /// <param name="format">The format with which to save the image.</param>
        private void Save(Surface2D surface, Stream stream, Bitmap.CompressFormat format)
        {
            var data = new Color[surface.Width * surface.Height];
            surface.GetData(data);

            Save(data, surface.Width, surface.Height, stream, format);
        }
Example #20
0
        void DrawBackground()
        {
            if (background != null) {
                background.Dispose ();
            }
            background = Bitmap.CreateBitmap(screen_size.Width, screen_size.Height, Bitmap.Config.Argb8888);
            Canvas c = new Canvas (background);
            //Paint black = new Paint();
            //black.SetARGB(255, 0, 0, 0);
            //black.SetStyle (Paint.Style.Stroke);
            //Bitmap plaatje = blokken[2].DrawBlok (MainActivity.context);

            //DrawBitmap werkt niet voor scaling bitmaps in xamarin
            //c.DrawBitmap (plaatje, new Rect (0, 0, plaatje.Width, plaatje.Height), new RectF (blokken[2].X, blokken[2].Y, blokken[2].Width, blokken[2].Height), null);
            //c.DrawBitmap(plaatje,96,0,null);

            foreach (Blok b in blokken)
            {
                Bitmap plaatje = b.DrawBlok (MainActivity.context);
                c.DrawBitmap (plaatje, b.X, b.Y, null);
                plaatje.Dispose ();
            }
            c.Dispose ();
            //black.Dispose ();
        }
Example #21
0
		// If you would like to create a circle of the image set pixels to half the width of the image.
		internal static   Bitmap GetRoundedCornerBitmap(Bitmap bitmap, int pixels)
		{
			Bitmap output = null;

			try
			{
				output = Bitmap.CreateBitmap(bitmap.Width, bitmap.Height, Bitmap.Config.Argb8888);
				Canvas canvas = new Canvas(output);

				Color color = new Color(66, 66, 66);
				Paint paint = new Paint();
				Rect rect = new Rect(0, 0, bitmap.Width, bitmap.Height);
				RectF rectF = new RectF(rect);
				float roundPx = pixels;

				paint.AntiAlias = true;
				canvas.DrawARGB(0, 0, 0, 0);
				paint.Color = color;
				canvas.DrawRoundRect(rectF, roundPx, roundPx, paint);

				paint.SetXfermode(new PorterDuffXfermode(PorterDuff.Mode.SrcIn));
				canvas.DrawBitmap(bitmap, rect, rect, paint);
			}
			catch (System.Exception err)
			{
				System.Console.WriteLine ("GetRoundedCornerBitmap Error - " + err.Message);
			}

			return output;
		}
        public static Bitmap decodeByteArray(byte[] buffer, int offset, int length)
        {
            JNIFind();

            if (_jcBitmapFactory == IntPtr.Zero)
            {
                Debug.LogError("_jcBitmapFactory is not initialized");
                return null;
            }
            if (_jmDecodeByteArray == IntPtr.Zero)
            {
                Debug.LogError("_jmDecodeByteArray is not initialized");
                return null;
            }
            IntPtr arg1 = AndroidJNI.ToByteArray(buffer);
            IntPtr retVal = AndroidJNI.CallStaticObjectMethod(_jcBitmapFactory, _jmDecodeByteArray, new jvalue[] { new jvalue() { l = arg1 }, new jvalue() { i = offset }, new jvalue() { i = length } });
            AndroidJNI.DeleteLocalRef(arg1);

            if (retVal == IntPtr.Zero)
            {
                Debug.LogError("decodeByteArray returned null bitmap");
                return null;
            }

            IntPtr globalRef = AndroidJNI.NewGlobalRef(retVal);
            AndroidJNI.DeleteLocalRef(retVal);

            Bitmap result = new Bitmap(globalRef);
            return result;
        }
Example #23
0
        // Rotates the bitmap by the specified degree.
        // If a new bitmap is created, the original bitmap is recycled.
        internal static Bitmap rotateImage(Bitmap b, int degrees)
        {
            if (degrees != 0 && b != null)
            {
                Matrix m = new Matrix();
                m.SetRotate(degrees,
                        (float)b.Width / 2, (float)b.Height / 2);
                try
                {
                    Bitmap b2 = Bitmap.CreateBitmap(
                            b, 0, 0, b.Width, b.Height, m, true);
                    if (b != b2)
                    {
                        b.Recycle();
                        b = b2;
                    }
                }
                catch (Java.Lang.OutOfMemoryError)
                {
                    // We have no memory to rotate. Return the original bitmap.
                }
            }

            return b;
        }
		public static Bitmap ToBlurred(Bitmap source, Context context, float radius)
		{
			if ((int)Android.OS.Build.VERSION.SdkInt >= 17)
			{
				Bitmap bitmap = Bitmap.CreateBitmap(source.Width, source.Height, Bitmap.Config.Argb8888);

				using (Canvas canvas = new Canvas(bitmap))
				{
					canvas.DrawBitmap(source, 0, 0, null);
					using (Android.Renderscripts.RenderScript rs = Android.Renderscripts.RenderScript.Create(context))
					{
						using (Android.Renderscripts.Allocation overlayAlloc = Android.Renderscripts.Allocation.CreateFromBitmap(rs, bitmap))
						{
							using (Android.Renderscripts.ScriptIntrinsicBlur blur = Android.Renderscripts.ScriptIntrinsicBlur.Create(rs, overlayAlloc.Element))
							{
								blur.SetInput(overlayAlloc);
								blur.SetRadius(radius);	
								blur.ForEach(overlayAlloc);
								overlayAlloc.CopyTo(bitmap);

								rs.Destroy();
								return bitmap;
							}
						}
					}
				}
			}

			return ToLegacyBlurred(source, context, (int)radius);
		}
		public SimulationView (Context context, SensorManager sensorManager, IWindowManager window)
			: base (context)
		{
			Bounds = new PointF ();

			// Get an accelorometer sensor
			sensor_manager = sensorManager;
			accel_sensor = sensor_manager.GetDefaultSensor (SensorType.Accelerometer);

			// Calculate screen size and dpi
			var metrics = new DisplayMetrics ();
			window.DefaultDisplay.GetMetrics (metrics);

			meters_to_pixels_x = metrics.Xdpi / 0.0254f;
			meters_to_pixels_y = metrics.Ydpi / 0.0254f;

			// Rescale the ball so it's about 0.5 cm on screen
			var ball = BitmapFactory.DecodeResource (Resources, Resource.Drawable.Ball);
			var dest_w = (int)(BALL_DIAMETER * meters_to_pixels_x + 0.5f);
			var dest_h = (int)(BALL_DIAMETER * meters_to_pixels_y + 0.5f);
			ball_bitmap = Bitmap.CreateScaledBitmap (ball, dest_w, dest_h, true);

			// Load the wood background texture
			var opts = new BitmapFactory.Options ();
			opts.InDither = true;
			opts.InPreferredConfig = Bitmap.Config.Rgb565;
			wood_bitmap = BitmapFactory.DecodeResource (Resources, Resource.Drawable.Wood, opts);
			wood_bitmap2 = BitmapFactory.DecodeResource (Resources, Resource.Drawable.Wood, opts);

			display = window.DefaultDisplay;
			particles = new ParticleSystem (this);
		}
        protected override void OnCreate(Bundle bundle)
        {
            //SetTheme(Resource.Style.Theme_Sherlock_Light);
            SetTheme(Resource.Style.Theme_Example);
            base.OnCreate(bundle);
            RequestWindowFeature(WindowFeatures.IndeterminateProgress);
            SetSupportProgressBarIndeterminateVisibility(false);
            Sherlock.ActionBar.SetDisplayHomeAsUpEnabled(true);

            SetContentView(Resource.Layout.Main);
            // Show tabs
            ActionBar.NavigationMode = ActionBarNavigationMode.Tabs;
            
            // attach adapter to the viewpager
            _pageAdapter = new ArtistPagerAdapter(SupportFragmentManager);
            _viewPager = FindViewById<ViewPager>(Resource.Id.myViewPager);
            _viewPager.Adapter = _pageAdapter;
            _viewPager.SetOnPageChangeListener(this);
            // startindex
            _viewPager.SetCurrentItem(0, true);

            var jsonArtist = Intent.GetStringExtra("Artist");
            _artist = JsonConvert.DeserializeObject<Artist>(jsonArtist);
            var jsonTopTracks = Intent.GetStringExtra("TopTracks");
            _topTracks = JsonConvert.DeserializeObject<TopTracks>(jsonTopTracks);
            var jsonTopAlbums = Intent.GetStringExtra("TopAlbums");
            _topAlbums = JsonConvert.DeserializeObject<TopAlbums>(jsonTopAlbums);

            _bitmapExtension = new BitmapExtension();
            try
            {
                _imageBitmap = _bitmapExtension.GetImageBitmapFromUrl(_artist.GetImageUrlOfSize("large"));
            }
            catch (Exception ex)
            {
                Toast.MakeText(this, "Error: " + ex.Message, ToastLength.Short).Show();
            }

            //TABS
            var tab1 = Sherlock.ActionBar.NewTab();
            tab1.SetText("Artist");
            tab1.SetTabListener(this);

            var tab2 = Sherlock.ActionBar.NewTab();
            tab2.SetText("Similar Artists");
            tab2.SetTabListener(this);

            var tab3 = Sherlock.ActionBar.NewTab();
            tab3.SetText("Top 15 Tracks");
            tab3.SetTabListener(this);

            var tab4 = Sherlock.ActionBar.NewTab();
            tab4.SetText("Top 5 Albums");
            tab4.SetTabListener(this);

            Sherlock.ActionBar.AddTab(tab1);
            Sherlock.ActionBar.AddTab(tab2);
            Sherlock.ActionBar.AddTab(tab3);
            Sherlock.ActionBar.AddTab(tab4);
        }
        public Bitmap OnFrameAvailable(Bitmap bitmap)
        {
            if (shouldBlur)
                return blur.BlurImage(bitmap);

            return bitmap;
        }
 public AchievementElement(string caption = null, string description = null, int percentageComplete = 0, Bitmap achievementImage = null)
     : base(caption, "dialog_achievements")
 {
     Description = description;
     PercentageComplete = percentageComplete;
     AchievementImage = achievementImage;
 }
 public static byte[] BitmapToByteArray(Bitmap bitmap)
 {
     ByteBuffer byteBuffer = ByteBuffer.Allocate(bitmap.ByteCount);
     bitmap.CopyPixelsToBuffer(byteBuffer);
     byte[] bytes = byteBuffer.ToArray<byte>();
     return bytes;
 }
        public Bitmap Transform(Bitmap source)
        {
            int size = Math.Min(source.Width, source.Height);

            int width = (source.Width - size) / 2;
            int height = (source.Height - size) / 2;

            var bitmap = Bitmap.CreateBitmap(size, size, Bitmap.Config.Argb4444);

            var canvas = new Canvas(bitmap);
            var paint = new Paint();
            var shader =
                new BitmapShader(source, BitmapShader.TileMode.Clamp, BitmapShader.TileMode.Clamp);
            if (width != 0 || height != 0)
            {
                // source isn't square, move viewport to center
                var matrix = new Matrix();
                matrix.SetTranslate(-width, -height);
                shader.SetLocalMatrix(matrix);
            }
            paint.SetShader(shader);
            paint.AntiAlias = true;

            float r = size / 2f;
            canvas.DrawCircle(r, r, r, paint);

            source.Recycle();

            return bitmap;
        }
Example #31
0
 public AndroidBitmap(int width, int height)
 {
     this.bmp = Android.Graphics.Bitmap.CreateBitmap(
         width,
         height,
         Android.Graphics.Bitmap.Config.Argb4444);
     this.Width  = width;
     this.Height = height;
 }
Example #32
0
 public static bool LoadSync(string filename, object[] nativeImageDataNativeData, List <Value> statusOutCheesy)
 {
     Android.Graphics.Bitmap nativeBmp = ResourceReader.ReadImageFile("ImageSheets/" + filename);
     if (nativeBmp != null)
     {
         AndroidBitmap bmp = new AndroidBitmap(nativeBmp);
         if (statusOutCheesy != null)
         {
             statusOutCheesy.Reverse();
         }
         nativeImageDataNativeData[0] = bmp;
         nativeImageDataNativeData[1] = bmp.Width;
         nativeImageDataNativeData[2] = bmp.Height;
         return(true);
     }
     return(false);
 }
Example #33
0
        protected override Android.Graphics.Bitmap Transform(Android.Graphics.Bitmap source)
        {
            Bitmap outBitmap = Bitmap.CreateBitmap(source.Width, source.Height, Bitmap.Config.Argb8888);
            Canvas canvas    = new Canvas(outBitmap);

            canvas.DrawBitmap(source, 0, 0, null);

            RenderScript        rs           = RenderScript.Create(mContext);
            Allocation          overlayAlloc = Allocation.CreateFromBitmap(rs, outBitmap);
            ScriptIntrinsicBlur blur         = ScriptIntrinsicBlur.Create(rs, overlayAlloc.Element);

            blur.SetInput(overlayAlloc);
            blur.SetRadius(mRadius);
            blur.ForEach(overlayAlloc);
            overlayAlloc.CopyTo(outBitmap);

            source.Recycle();
            rs.Destroy();

            return(outBitmap);
        }
Example #34
0
        public static void DrawResults(Android.Graphics.Bitmap bmp, MultiboxGraph.Result result, float scoreThreshold)
        {
            Rectangle[] locations = ScaleLocation(result.DecodedLocations, bmp.Width, bmp.Height);

            Android.Graphics.Paint p = new Android.Graphics.Paint();
            p.SetStyle(Paint.Style.Stroke);
            p.AntiAlias = true;
            p.Color     = Android.Graphics.Color.Red;
            Canvas c = new Canvas(bmp);


            for (int i = 0; i < result.Scores.Length; i++)
            {
                if (result.Scores[i] > scoreThreshold)
                {
                    Rectangle             rect = locations[result.Indices[i]];
                    Android.Graphics.Rect r    = new Rect(rect.Left, rect.Top, rect.Right, rect.Bottom);
                    c.DrawRect(r, p);
                }
            }
        }
Example #35
0
        public async Task <byte[]> Capture()
        {
            await Task.Yield();

            View rootView = CrossCurrentActivity.Current.Activity.Window.DecorView.RootView;

            using (Bitmap screenshot = Android.Graphics.Bitmap.CreateBitmap(
                       rootView.Width,
                       rootView.Height,
                       Android.Graphics.Bitmap.Config.Argb8888))
            {
                Canvas canvas = new (screenshot);
                rootView.Draw(canvas);

                using (MemoryStream stream = new ())
                {
                    screenshot.Compress(Android.Graphics.Bitmap.CompressFormat.Png, 90, stream);
                    return(stream.ToArray());
                }
            }
        }
        private void InitViewsFunc()
        {
            selecionar.Click += async delegate
            {
                try
                {
                    photo = await MediaPicker.PickPhotoAsync();

                    bitmap = BitmapFactory.DecodeFile(photo.FullPath);
                    previewImage.SetImageBitmap(bitmap);
                }catch (NullReferenceException)
                {
                    alert("Nenhuma imagem selecionada!");
                }catch (Exception e)
                {
                    Console.WriteLine("Err: " + e.ToString());
                }
            };

            imprimir.Click += delegate
            {
                parametros = new Dictionary <string, string>();

                if (photo == null || photo.FullPath == "")
                {
                    parametros.Add("pathImage", "elgin");
                }
                else
                {
                    parametros.Add("pathImage", photo.FullPath);
                }
                parametros.Add("isBase64", "false");
                Printer.imprimeImagem(parametros);
                Printer.AvancaLinhas(10);
                if (checkboxcutPaper.Checked)
                {
                    Printer.cutPaper(10);
                }
            };
        }
Example #37
0
        public bool WriteFile(Mat mat, String fileName)
        {
            try
            {
                FileInfo fileInfo = new FileInfo(fileName);
                using (Android.Graphics.Bitmap bmp = mat.ToBitmap())
                    using (FileStream fs = fileInfo.Open(FileMode.Append, FileAccess.Write))
                    {
                        String extension = fileInfo.Extension.ToLower();
                        Debug.Assert(extension.Substring(0, 1).Equals("."));
                        switch (extension)
                        {
                        case ".jpg":
                        case ".jpeg":
                            bmp.Compress(Android.Graphics.Bitmap.CompressFormat.Jpeg, 90, fs);
                            break;

                        case ".png":
                            bmp.Compress(Android.Graphics.Bitmap.CompressFormat.Png, 90, fs);
                            break;

                        case ".webp":
                            bmp.Compress(Android.Graphics.Bitmap.CompressFormat.Webp, 90, fs);
                            break;

                        default:
                            throw new NotImplementedException(String.Format("Saving to {0} format is not supported",
                                                                            extension));
                        }
                    }

                return(true);
            }
            catch (Exception e)
            {
                Debug.WriteLine(e);
                //throw;
                return(false);
            }
        }
Example #38
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            // Create your application here
            SetContentView(Resource.Layout.PlantingCampignIssue1);


            addLocation        = FindViewById <ImageView>(Resource.Id.Planting_AddLocation);
            addLocation.Click += AddLocation_Click;

            tvusername = (TextView)FindViewById(Resource.Id.tvusername);
            tf         = Typeface.CreateFromAsset(Assets, "Quicksand-Bold.otf");
            tvusername.SetTypeface(tf, TypefaceStyle.Bold);

            //runtime py profile change krna or name change krna
            //start
            circleImageViewplanting = (CircleImageView)FindViewById(Resource.Id.circleImageView2);
            char[] arr = Control.UserInfoHolder.User_name.ToCharArray();
            tvusername.SetText(arr, 0, arr.Length);
            byte[] arra = Convert.FromBase64String(Control.UserInfoHolder.Profile_pic);


            Android.Graphics.Bitmap bitmapp = BitmapFactory.DecodeByteArray(arra, 0, arra.Length);
            circleImageViewplanting.SetImageBitmap(bitmapp);
            //end

            tev1 = (TextView)FindViewById(Resource.Id.tev1);
            Typeface.CreateFromAsset(Assets, "Quicksand-Bold.otf");
            tev1.SetTypeface(tf, TypefaceStyle.Bold);

            tvinfoproblem = (TextView)FindViewById(Resource.Id.tvinfoproblem);
            tf            = Typeface.CreateFromAsset(Assets, "Quicksand-Bold.otf");
            tvinfoproblem.SetTypeface(tf, TypefaceStyle.Bold);
            iconback        = (ImageView)FindViewById(Resource.Id.backbtn6);
            iconback.Click += Iconback_Click;
            close           = (ImageView)FindViewById(Resource.Id.close);
            close.Click    += Close_Click;
        }
Example #39
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            // Create your application here
            SetContentView(Resource.Layout.Manhole1);

            Manhole1_radiobtn1        = (RadioButton)FindViewById(Resource.Id.Manhole1_radiobtn1);
            Manhole1_radiobtn1.Click += Manhole1_radiobtn1_Click;
            Manhole1_radiobtn2        = (RadioButton)FindViewById(Resource.Id.Manhole1_radiobtn2);
            Manhole1_radiobtn2.Click += Manhole1_radiobtn2_Click;
            Manhole1_radio1           = (ImageView)FindViewById(Resource.Id.iconIssue1);
            Manhole1_radio1.Click    += Manhole1_radio1_Click;
            Manhole1_radio2           = (ImageView)FindViewById(Resource.Id.iconIssue2);
            Manhole1_radio2.Click    += Manhole1_radio2_Click;
            back        = (ImageView)FindViewById(Resource.Id.btnback);
            back.Click += Back_Click;
            circleImageView_Manhole1 = (CircleImageView)FindViewById(Resource.Id.circleImageView_Manhole1);

            Manhole1_next        = (ImageView)FindViewById(Resource.Id.Manhole1_btnnext);
            Manhole1_next.Click += Manhole1_next_Click;

            Manhole1_tvusername = (TextView)FindViewById(Resource.Id.Manhole1_tvusername);
            Manhole1_tv         = (TextView)FindViewById(Resource.Id.Manhole1_tv);
            tev1 = (TextView)FindViewById(Resource.Id.tev1);
            //runtime py profile change krna or name change krna
            //start

            char[] arr = Control.UserInfoHolder.User_name.ToCharArray();
            Manhole1_tvusername.SetText(arr, 0, arr.Length);
            byte[] arra = Convert.FromBase64String(Control.UserInfoHolder.Profile_pic);

            ImageView img2 = FindViewById <ImageView>(Resource.Id.circleImageView_Manhole1);

            Android.Graphics.Bitmap bitmapp = BitmapFactory.DecodeByteArray(arra, 0, arra.Length);
            img2.SetImageBitmap(bitmapp);
            //end
        }
        private void BindViews()
        {
            if (entrega == null)
            {
                return;
            }

            txtCodigoNF.Text    = entrega.ds_NFE;
            spinOcorrencia      = entrega.id_ocorrencia.ToString();
            txtDataEntrega.Text = entrega.dt_entrega.Value.ToString("dd/MM/yyyy");
            txtHoraEntrega.Text = entrega.dt_entrega.Value.ToString("HH:mm");
            txtObservacao.Text  = entrega.ds_observacao.ToString();

            Substring_Helper sub = new Substring_Helper();

            lblCNPJ.Text     = "CNPJ Emissor: " + sub.Substring_CNPJ(entrega.ds_NFE);
            lblNumeroNF.Text = "Número NF: " + sub.Substring_NumeroNF(entrega.ds_NFE) + "/" + sub.Substring_SerieNota(entrega.ds_NFE);

            if (entrega.Image != null)
            {
                ByteHelper helper = new ByteHelper();
                bitmap = helper.ByteArrayToImage(entrega.Image);
                imageView.SetImageBitmap(bitmap);
            }

            if (entrega.ds_geolocalizacao == null || entrega.ds_geolocalizacao == "")
            {
                txtGeolocalizacao.Visibility = ViewStates.Gone;
                lblGeolocalizacao.Visibility = ViewStates.Gone;
            }
            else if (entrega.ds_geolocalizacao != null || entrega.ds_geolocalizacao != "")
            {
                lblGeolocalizacao.Visibility = ViewStates.Visible;
                txtGeolocalizacao.Visibility = ViewStates.Visible;
                txtGeolocalizacao.Text       = entrega.ds_geolocalizacao.ToString();
            }
            checkBoxGeolocalizacao.Visibility = ViewStates.Gone;
        }
        public Android.Graphics.Bitmap ToGrayscale(Android.Graphics.Bitmap bmpOriginal)
        {
            int width, height;

            height = bmpOriginal.Height;
            width  = bmpOriginal.Width;

            float[] mat = new float[] {
                0.3f, 0.59f, 0.11f, 0, 0,
                0.3f, 0.59f, 0.11f, 0, 0,
                0.3f, 0.59f, 0.11f, 0, 0,
                0, 0, 0, 1, 0,
            };

            Android.Graphics.Bitmap bmpGrayscale = Android.Graphics.Bitmap.CreateBitmap(width, height, Android.Graphics.Bitmap.Config.Argb8888);
            GC.Collect();
            Android.Graphics.Canvas c = new Android.Graphics.Canvas(bmpGrayscale);
            Android.Graphics.ColorMatrixColorFilter filter = new Android.Graphics.ColorMatrixColorFilter(mat);
            Android.Graphics.Paint paint = new Android.Graphics.Paint();
            paint.SetColorFilter(filter);
            c.DrawBitmap(bmpOriginal, 0, 0, paint);
            return(bmpGrayscale);
        }
Example #42
0
        /// <summary>
        /// 连接两张图片,并返回连接后的图像。如果两张图片大小不一致,小的那张将适当居中。
        /// </summary>
        /// <param name="img1">图片1</param>
        /// <param name="img2">图片2</param>
        /// <param name="direction">连接方向,默认为"RIGHT",可选的值有:
        ///    LEFT 将图片2接到图片1左边
        ///    RIGHT 将图片2接到图片1右边
        ///    TOP 将图片2接到图片1上边
        ///    BOTTOM 将图片2接到图片1下边
        /// </param>
        /// <returns></returns>
        public ImageWrapper concat(ImageWrapper img1, ImageWrapper img2, GravityFlags direction)
        {
            int width;
            int height;

            if (direction == GravityFlags.Left || direction == GravityFlags.Top)
            {
                var tmp = img1;
                img1 = img2;
                img2 = tmp;
            }

            if (direction == GravityFlags.Left || direction == GravityFlags.Right)
            {
                width  = img1.Width + img2.Width;
                height = Math.Max(img1.Height, img2.Height);
            }
            else
            {
                width  = Math.Max(img1.Width, img2.Height);
                height = img1.Height + img2.Height;
            }

            var bitmap = Bitmap.CreateBitmap(width, height, Bitmap.Config.Argb8888);
            var canvas = new Canvas();
            var paint  = new Paint();

            if (direction != GravityFlags.Left && direction != GravityFlags.Right)
            {
                return(ImageWrapper.OfBitmap(bitmap));
            }

            canvas.DrawBitmap(img1.Bitmap, (width - img1.Width) / 2, 0, paint);
            canvas.DrawBitmap(img2.Bitmap, (width - img2.Width) / 2, img1.Height, paint);

            return(ImageWrapper.OfBitmap(bitmap));
        }
Example #43
0
        private async void TomarFoto(object sender, EventArgs e)
        {
            await CrossMedia.Current.Initialize();

            if (!CrossMedia.Current.IsTakePhotoSupported || !CrossMedia.Current.IsCameraAvailable)
            {
                await DisplayAlert("Ops", "Camara no detectada", "OK");

                return;
            }

            var file = await CrossMedia.Current.TakePhotoAsync(
                new StoreCameraMediaOptions
            {
                SaveToAlbum = true,
                Directory   = "Horus"
            });

            if (file == null)
            {
                return;
            }

            this.Preview.Source = ImageSource.FromStream(() =>
            {
                var stream = file.GetStream();

                return(stream);
            });

            // LEEMOS LA IMAGEN, LA REESCALAMOS Y LA SUBIMOS A LA API
            Android.Graphics.Bitmap Imagen = scaleDown(BitmapFactory.DecodeFile(file.AlbumPath), 800, false);

            Upload(Imagen);

            file.Dispose();
        }
        private void NegateRed(object sender, System.EventArgs e)
        {
            TextView  tv_saved  = FindViewById <TextView>(Resource.Id.respondText);
            ImageView imageView = FindViewById <ImageView>(Resource.Id.takenPictureImageView);
            int       height    = Resources.DisplayMetrics.HeightPixels;
            int       width     = imageView.Height;

            Android.Graphics.Bitmap bitmap     = _file.Path.LoadAndResizeBitmap(width, height);
            Android.Graphics.Bitmap copyBitmap = bitmap.Copy(Android.Graphics.Bitmap.Config.Argb8888, true);
            for (int i = 0; i < copyBitmap.Width; i++)
            {
                for (int j = 0; j < copyBitmap.Height; j++)
                {
                    int p = copyBitmap.GetPixel(i, j);
                    //00000000 00000000 00000000 00000000
                    //long mask = (long)0xFF00FFFF;
                    //p = p & (int)mask;
                    Color myColor            = new Color(copyBitmap.GetPixel(i, j));
                    byte  myColorRedValue    = myColor.R;
                    byte  myColorBlueValue   = myColor.B;
                    byte  myColorGreenValue  = myColor.G;
                    byte  myColorAlphaValue  = myColor.A;
                    Android.Graphics.Color c = new Android.Graphics.Color(p);
                    c.R = (byte)(255 - myColor);
                    copyBitmap.SetPixel(i, j, c);
                }
            }
            if (bitmap != null)
            {
                imageView.SetImageBitmap(copyBitmap);
                imageView.Visibility = Android.Views.ViewStates.Visible;
            }

            System.GC.Collect();
            tv_saved.SetTextKeepState("Red Negated!");
        }
Example #45
0
        public static AG.Bitmap Scale(this AG.Bitmap bitemap, SD.Size dstSize, bool keepAspect = true)
        {
            if (keepAspect)
            {
                var ratio = 1f;
                if (bitemap.Width > bitemap.Height)
                {
                    ratio          = (float)bitemap.Height / (float)bitemap.Width;
                    dstSize.Height = (int)(dstSize.Height * ratio);
                }
                else
                {
                    ratio         = (float)bitemap.Width / (float)bitemap.Height;
                    dstSize.Width = (int)(dstSize.Width * ratio);
                }
            }

            var width  = dstSize.Width;
            var height = dstSize.Height;

            var scaled = AG.Bitmap.CreateScaledBitmap(bitemap, width, height, true);

            return(scaled);
        }
        //CircleImageView userimage;
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            SetContentView(Resource.Layout.Ads);


            // Create your fragment here
            back        = (ImageView)FindViewById(Resource.Id.imgbackgo);
            back.Click += Back_Click;
            Username    = (TextView)FindViewById(Resource.Id.username);

            userimage        = (CircleImageView)FindViewById(Resource.Id.usericon);
            crtNewAd         = (ImageView)FindViewById(Resource.Id.imgcrtnewads);
            crtNewAd.Click  += CrtNewAd_Click;
            manageAds        = (ImageView)FindViewById(Resource.Id.imgManageAds);
            manageAds.Click += ManageAds_Click;
            //runtime py name and user image change start
            char[] arr  = UserInfoHolder.User_name.ToCharArray();
            byte[] arra = Convert.FromBase64String(Control.UserInfoHolder.Profile_pic);
            Android.Graphics.Bitmap bitmapp = BitmapFactory.DecodeByteArray(arra, 0, arra.Length);
            userimage.SetImageBitmap(bitmapp);
            Username.SetText(arr, 0, arr.Length);
            //end
        }
Example #47
0
 protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
 {
     if (requestCode == CAPTURE_PHOTO)
     {
         if (resultCode == Result.Ok)
         {    // display saved image
             Android.Graphics.Bitmap poiImage = POIData.GetImageFile(_poi.Id.Value);
             _poiImageView.SetImageBitmap(poiImage);
             if (poiImage != null)
             {
                 poiImage.Dispose();
             }
         }
         else        // let the user know the photo was cancelled
         {
             Toast toast = Toast.MakeText(this, "No picture captured.", ToastLength.Short);
             toast.Show();
         }
     }
     else
     {
         base.OnActivityResult(requestCode, resultCode, data);
     }
 }
        // <summary>
        // Called automatically whenever an activity finishes
        // </summary>
        // <param name = "requestCode" ></ param >
        // < param name="resultCode"></param>
        /// <param name="data"></param>
        protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
        {
            base.OnActivityResult(requestCode, resultCode, data);

            //AC: workaround for not passing actual files
            Android.Graphics.Bitmap bitmap = (Android.Graphics.Bitmap)data.Extras.Get("data");

            //scale image to make manipulation easier
            copy_bitmap = Android.Graphics.Bitmap.CreateScaledBitmap(bitmap, 1024, 768, true);

            //change layout to the editor
            SetContentView(Resource.Layout.Editor);

            //grab imageview and display bitmap
            ImageView editView = FindViewById <ImageView>(Resource.Id.editImage);

            if (copy_bitmap != null)
            {
                editView.SetImageBitmap(copy_bitmap);
            }

            // Dispose of the Java side bitmap.
            System.GC.Collect();

            //Set button clicks to functions
            FindViewById <Button>(Resource.Id.remRed).Click       += removeRed;
            FindViewById <Button>(Resource.Id.remBlue).Click      += removeBlue;
            FindViewById <Button>(Resource.Id.remGreen).Click     += removeGreen;
            FindViewById <Button>(Resource.Id.negRed).Click       += negateRed;
            FindViewById <Button>(Resource.Id.negBlue).Click      += negateBlue;
            FindViewById <Button>(Resource.Id.negGreen).Click     += negateGreen;
            FindViewById <Button>(Resource.Id.grayScale).Click    += grayScale;
            FindViewById <Button>(Resource.Id.highContrast).Click += highContrast;
            FindViewById <Button>(Resource.Id.addNoise).Click     += addNoise;
            FindViewById <Button>(Resource.Id.Done).Click         += done;
        }
Example #49
0
        public static Tensor ReadTensorFromImageFile(String fileName, int inputHeight = -1, int inputWidth = -1, float inputMean = 0.0f, float scale = 1.0f, Status status = null)
        {
#if __ANDROID__
            Android.Graphics.Bitmap bmp = BitmapFactory.DecodeFile(fileName);

            if (inputHeight > 0 || inputWidth > 0)
            {
                Bitmap resized = Bitmap.CreateScaledBitmap(bmp, inputWidth, inputHeight, false);
                bmp.Dispose();
                bmp = resized;
            }
            int[]   intValues   = new int[bmp.Width * bmp.Height];
            float[] floatValues = new float[bmp.Width * bmp.Height * 3];
            bmp.GetPixels(intValues, 0, bmp.Width, 0, 0, bmp.Width, bmp.Height);
            for (int i = 0; i < intValues.Length; ++i)
            {
                int val = intValues[i];
                floatValues[i * 3 + 0] = (((val >> 16) & 0xFF) - inputMean) * scale;
                floatValues[i * 3 + 1] = (((val >> 8) & 0xFF) - inputMean) * scale;
                floatValues[i * 3 + 2] = ((val & 0xFF) - inputMean) * scale;
            }

            Tensor t = new Tensor(DataType.Float, new int[] { 1, bmp.Height, bmp.Width, 3 });
            System.Runtime.InteropServices.Marshal.Copy(floatValues, 0, t.DataPointer, floatValues.Length);
            return(t);
#elif __IOS__
            UIImage image = new UIImage(fileName);
            if (inputHeight > 0 || inputWidth > 0)
            {
                UIImage resized = image.Scale(new CGSize(inputWidth, inputHeight));
                image.Dispose();
                image = resized;
            }
            int[]   intValues   = new int[(int)(image.Size.Width * image.Size.Height)];
            float[] floatValues = new float[(int)(image.Size.Width * image.Size.Height * 3)];
            System.Runtime.InteropServices.GCHandle handle = System.Runtime.InteropServices.GCHandle.Alloc(intValues, System.Runtime.InteropServices.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();

            for (int i = 0; i < intValues.Length; ++i)
            {
                int val = intValues[i];
                floatValues[i * 3 + 0] = (((val >> 16) & 0xFF) - inputMean) * scale;
                floatValues[i * 3 + 1] = (((val >> 8) & 0xFF) - inputMean) * scale;
                floatValues[i * 3 + 2] = ((val & 0xFF) - inputMean) * scale;
            }

            Tensor t = new Tensor(DataType.Float, new int[] { 1, (int)image.Size.Height, (int)image.Size.Width, 3 });
            System.Runtime.InteropServices.Marshal.Copy(floatValues, 0, t.DataPointer, floatValues.Length);
            return(t);
#else
            if (Emgu.TF.Util.Platform.OperationSystem == OS.Windows)
            {
                Tensor t = new Tensor(DataType.Float, new int[] { 1, (int)inputHeight, (int)inputWidth, 3 });
                NativeImageIO.ReadImageFileToTensor(fileName, t.DataPointer, inputHeight, inputWidth, inputMean, scale);
                return(t);
            }
            else
            {
                using (StatusChecker checker = new StatusChecker(status))
                {
                    var       graph = new Graph();
                    Operation input = graph.Placeholder(DataType.String);

                    Operation jpegDecoder = graph.DecodeJpeg(input, 3);                    //dimension 3

                    Operation floatCaster = graph.Cast(jpegDecoder, DstT: DataType.Float); //cast to float

                    Tensor    axis         = new Tensor(0);
                    Operation axisOp       = graph.Const(axis, axis.Type, opName: "axis");
                    Operation dimsExpander = graph.ExpandDims(floatCaster, axisOp); //turn it to dimension [1,3]

                    Operation resized;
                    bool      resizeRequired = (inputHeight > 0) && (inputWidth > 0);
                    if (resizeRequired)
                    {
                        Tensor    size   = new Tensor(new int[] { inputHeight, inputWidth }); // new size;
                        Operation sizeOp = graph.Const(size, size.Type, opName: "size");
                        resized = graph.ResizeBilinear(dimsExpander, sizeOp);                 //resize image
                    }
                    else
                    {
                        resized = dimsExpander;
                    }

                    Tensor    mean        = new Tensor(inputMean);
                    Operation meanOp      = graph.Const(mean, mean.Type, opName: "mean");
                    Operation substracted = graph.Sub(resized, meanOp);

                    Tensor    scaleTensor = new Tensor(scale);
                    Operation scaleOp     = graph.Const(scaleTensor, scaleTensor.Type, opName: "scale");
                    Operation scaled      = graph.Mul(substracted, scaleOp);

                    Session  session      = new Session(graph);
                    Tensor   imageTensor  = Tensor.FromString(File.ReadAllBytes(fileName), status);
                    Tensor[] imageResults = session.Run(new Output[] { input }, new Tensor[] { imageTensor },
                                                        new Output[] { scaled });
                    return(imageResults[0]);
                }
            }
#endif
        }
Example #50
0
 /// <summary>
 /// Load the specific file using Bitmap
 /// </summary>
 /// <param name="file">The file to load</param>
 private void LoadFileUsingBitmap(FileInfo file)
 {
     using (Android.Graphics.Bitmap bmp = Android.Graphics.BitmapFactory.DecodeFile(file.FullName))
         Bitmap = bmp;
 }
Example #51
0
 public void DrawResultBitmap(Android.Graphics.Bitmap barcode)
 {
     resultBitmap = barcode;
     Invalidate();
 }
Example #52
0
 /// <summary>
 /// 添加中心菜单按钮
 /// </summary>
 /// <param name="coreMenuColor"> </param>
 /// <param name="coreMenuSelectColor"> </param>
 /// <param name="onClickListener"> </param>
 public virtual void SetCoreMenu(int coreMenuColor, int coreMenuSelectColor, int coreMenuStrokeColor, int coreMenuStrokeSize, double radiusDistance, Bitmap bitmap, IOnClickListener onClickListener)
 {
     isCoreMenu               = true;
     this.coreMenuColor       = coreMenuColor;
     this.radiusDistance      = radiusDistance;
     this.coreMenuSelectColor = coreMenuSelectColor;
     this.coreMenuStrokeColor = coreMenuStrokeColor;
     this.coreMenuStrokeSize  = coreMenuStrokeSize;
     coreBitmap               = bitmap;
     this.onCoreClickListener = onClickListener;
     Invalidate();
 }
Example #53
0
 /// <summary>
 /// Read image file from Assets
 /// </summary>
 /// <param name="assets">The Asset manager</param>
 /// <param name="fileName">The name of the file</param>
 public Image(AssetManager assets, String fileName)
 {
     using (Stream imageStream = assets.Open(fileName))
         using (Android.Graphics.Bitmap imageBmp = BitmapFactory.DecodeStream(imageStream))
             Bitmap = imageBmp;
 }
Example #54
0
        /// <summary>
        /// Read the file and draw rectangles on it.
        /// </summary>
        /// <param name="fileName">The name of the file.</param>
        /// <param name="annotations">Annotations to be add to the image. Can consist of rectangles and lables</param>
        /// <returns>The image in Jpeg stream format</returns>
        public static byte[] ImageFileToJpeg(String fileName, Annotation[] annotations = null)
        {
#if __ANDROID__
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.InMutable = true;
            Android.Graphics.Bitmap bmp = BitmapFactory.DecodeFile(fileName, options);

            Android.Graphics.Paint p = new Android.Graphics.Paint();
            p.SetStyle(Paint.Style.Stroke);
            p.AntiAlias = true;
            p.Color     = Android.Graphics.Color.Red;
            Canvas c = new Canvas(bmp);

            for (int i = 0; i < annotations.Length; i++)
            {
                float[] rects           = ScaleLocation(annotations[i].Rectangle, bmp.Width, bmp.Height);
                Android.Graphics.Rect r = new Rect((int)rects[0], (int)rects[1], (int)rects[2], (int)rects[3]);
                c.DrawRect(r, p);
            }

            using (MemoryStream ms = new MemoryStream())
            {
                bmp.Compress(Bitmap.CompressFormat.Jpeg, 90, ms);
                return(ms.ToArray());
            }
#elif __MACOS__
            NSImage img = NSImage.ImageNamed(fileName);

            DrawAnnotations(img, annotations);

            /*
             * img.LockFocus();
             *
             * NSColor redColor = NSColor.Red;
             * redColor.Set();
             * var context = NSGraphicsContext.CurrentContext;
             * var cgcontext = context.CGContext;
             * cgcontext.ScaleCTM(1, -1);
             * cgcontext.TranslateCTM(0, -img.Size.Height);
             * //context.IsFlipped = !context.IsFlipped;
             * for (int i = 0; i < annotations.Length; i++)
             * {
             *  float[] rects = ScaleLocation(annotations[i].Rectangle, (int)img.Size.Width, (int) img.Size.Height);
             *  CGRect cgRect = new CGRect(
             *      rects[0],
             *      rects[1],
             *      rects[2] - rects[0],
             *      rects[3] - rects[1]);
             *  NSBezierPath.StrokeRect(cgRect);
             * }
             * img.UnlockFocus();
             */

            var    imageData = img.AsTiff();
            var    imageRep  = NSBitmapImageRep.ImageRepsWithData(imageData)[0] as NSBitmapImageRep;
            var    jpegData  = imageRep.RepresentationUsingTypeProperties(NSBitmapImageFileType.Jpeg, null);
            byte[] jpeg      = new byte[jpegData.Length];
            System.Runtime.InteropServices.Marshal.Copy(jpegData.Bytes, jpeg, 0, (int)jpegData.Length);
            return(jpeg);
#elif __IOS__
            UIImage uiimage = new UIImage(fileName);

            UIGraphics.BeginImageContextWithOptions(uiimage.Size, false, 0);
            var context = UIGraphics.GetCurrentContext();

            uiimage.Draw(new CGPoint());
            context.SetStrokeColor(UIColor.Red.CGColor);
            context.SetLineWidth(2);
            for (int i = 0; i < annotations.Length; i++)
            {
                float[] rects = ScaleLocation(
                    annotations[i].Rectangle,
                    (int)uiimage.Size.Width,
                    (int)uiimage.Size.Height);
                CGRect cgRect = new CGRect(
                    (nfloat)rects[0],
                    (nfloat)rects[1],
                    (nfloat)(rects[2] - rects[0]),
                    (nfloat)(rects[3] - rects[1]));
                context.AddRect(cgRect);
                context.DrawPath(CGPathDrawingMode.Stroke);
            }
            UIImage imgWithRect = UIGraphics.GetImageFromCurrentImageContext();
            UIGraphics.EndImageContext();

            var    jpegData = imgWithRect.AsJPEG();
            byte[] jpeg     = new byte[jpegData.Length];
            System.Runtime.InteropServices.Marshal.Copy(jpegData.Bytes, jpeg, 0, (int)jpegData.Length);
            return(jpeg);
#else
            if (Emgu.TF.Util.Platform.OperationSystem == OS.Windows)
            {
                Bitmap img = new Bitmap(fileName);

                if (annotations != null)
                {
                    using (Graphics g = Graphics.FromImage(img))
                    {
                        for (int i = 0; i < annotations.Length; i++)
                        {
                            if (annotations[i].Rectangle != null)
                            {
                                float[]    rects  = ScaleLocation(annotations[i].Rectangle, img.Width, img.Height);
                                PointF     origin = new PointF(rects[0], rects[1]);
                                RectangleF rect   = new RectangleF(rects[0], rects[1], rects[2] - rects[0], rects[3] - rects[1]);
                                Pen        redPen = new Pen(Color.Red, 3);
                                g.DrawRectangle(redPen, Rectangle.Round(rect));

                                String label = annotations[i].Label;
                                if (label != null)
                                {
                                    g.DrawString(label, new Font(FontFamily.GenericSansSerif, 20f), Brushes.Red, origin);
                                }
                            }
                        }
                        g.Save();
                    }
                }

                using (MemoryStream ms = new MemoryStream())
                {
                    img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                    return(ms.ToArray());
                }
            }
            else
            {
                throw new Exception("DrawResultsToJpeg Not implemented for this platform");
            }
#endif
        }
Example #55
0
        protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
        {
            base.OnActivityResult(requestCode, resultCode, data);
            try
            {
                if (resultCode == Result.Ok)
                {
                    if (requestCode == 1)
                    {
                        try {
                            Android.Net.Uri selectImage = data.Data;
                            imageUrl1       = getRealPathFromURI(data.Data);
                            imageurlId1     = data.Data.LastPathSegment;
                            datetimedetalle = System.IO.File.GetLastAccessTimeUtc(imageUrl1);
                            string fechahora = datetimedetalle.Day.ToString() + datetimedetalle.Month.ToString() + datetimedetalle.Year.ToString().Substring(2, 2) + "-" + datetimedetalle.Hour.ToString() + datetimedetalle.Minute.ToString();

                            GC.Collect();
                            if (System.IO.File.Exists(imageUrl1))
                            {
                                Android.Graphics.Bitmap bitmap = Utils.ChangeSizeBitmap(BitmapFactory.DecodeFile(imageUrl1), 1600, 1200);

                                using (MemoryStream stream = new MemoryStream()) {
                                    bitmap.Compress(Android.Graphics.Bitmap.CompressFormat.Jpeg, 100, stream);
                                    bitmapDetalle = stream.ToArray();
                                    stream.Flush();
                                    stream.Close();
                                }

                                bitmap.Dispose();
                                if (bitmapDetalle == null)
                                {
                                    Toast.MakeText(ApplicationContext, "No se cargó la fotografía correctamente, favor de seleccionarla de nuevo", ToastLength.Long).Show();
                                    return;
                                }
                                else
                                {
                                    lblFotoDetalle.Text = ODTDet.Folio + " - Detalle - " + fechahora + ".jpg";
                                }
                            }
                        } catch (Exception exc) {
                            Toast.MakeText(ApplicationContext, "No se cargó la fotografía correctamente, favor de seleccionarla de nuevo", ToastLength.Long).Show();
                            return;
                        }
                    }
                    else if (requestCode == 2)
                    {
                        try {
                            Android.Net.Uri selectImage = data.Data;
                            imageUrl2       = getRealPathFromURI(data.Data);
                            imageurlId2     = data.Data.LastPathSegment;
                            datetimemediana = System.IO.File.GetLastAccessTimeUtc(imageUrl2);
                            string fechahora = datetimemediana.Day.ToString() + datetimemediana.Month.ToString() + datetimemediana.Year.ToString().Substring(2, 2) + "-" + datetimemediana.Hour.ToString() + datetimemediana.Minute.ToString();

                            GC.Collect();

                            if (System.IO.File.Exists(imageUrl2))
                            {
                                Android.Graphics.Bitmap bitmap = Utils.ChangeSizeBitmap(BitmapFactory.DecodeFile(imageUrl2), 1600, 1200);

                                using (MemoryStream stream = new MemoryStream()) {
                                    bitmap.Compress(Android.Graphics.Bitmap.CompressFormat.Jpeg, 100, stream);
                                    bitmapMediana = stream.ToArray();
                                    stream.Flush();
                                    stream.Close();
                                }

                                bitmap.Dispose();
                                if (bitmapMediana == null)
                                {
                                    Toast.MakeText(ApplicationContext, "No se cargó la fotografía correctamente, favor de seleccionarla de nuevo", ToastLength.Long).Show();
                                    return;
                                }
                                else
                                {
                                    lblFotoMediana.Text = ODTDet.Folio + " - Mediana - " + fechahora + ".jpg";
                                }
                            }
                        } catch (Exception exc) {
                            Toast.MakeText(ApplicationContext, "No se cargó la fotografía correctamente, favor de seleccionarla de nuevo", ToastLength.Long).Show();
                            return;
                        }
                    }
                    else if (requestCode == 3)
                    {
                        try {
                            Android.Net.Uri selectImage = data.Data;
                            imageUrl3     = getRealPathFromURI(data.Data);
                            imageurlId3   = data.Data.LastPathSegment;
                            datetimelarga = System.IO.File.GetLastAccessTimeUtc(imageUrl3);

                            string fechahora = datetimelarga.Day.ToString() + datetimelarga.Month.ToString() + datetimelarga.Year.ToString().Substring(2, 2) + "-" + datetimelarga.Hour.ToString() + datetimelarga.Minute.ToString();

                            GC.Collect();
                            if (System.IO.File.Exists(imageUrl3))
                            {
                                Android.Graphics.Bitmap bitmap = Utils.ChangeSizeBitmap(BitmapFactory.DecodeFile(imageUrl3), 1600, 1200);

                                using (MemoryStream stream = new MemoryStream()) {
                                    bitmap.Compress(Android.Graphics.Bitmap.CompressFormat.Jpeg, 100, stream);
                                    bitmapLarga = stream.ToArray();
                                    stream.Flush();
                                    stream.Close();
                                }

                                bitmap.Dispose();
                                if (bitmapLarga == null)
                                {
                                    Toast.MakeText(ApplicationContext, "No se cargó la fotografía correctamente, favor de seleccionarla de nuevo", ToastLength.Long).Show();
                                    return;
                                }
                                else
                                {
                                    lblFotoLarga.Text = ODTDet.Folio + " - Larga - " + fechahora + ".jpg";
                                }
                            }
                        } catch (Exception exc) {
                            Toast.MakeText(ApplicationContext, "No se cargó la fotografía correctamente, favor de seleccionarla de nuevo", ToastLength.Long).Show();
                            return;
                        }
                    }
                    else if (requestCode == 4)                //extSdCard

                    {
                        try{
                            if (App._file.Exists())
                            {
                                if (Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.Kitkat)
                                {
                                    Intent mediaScanIntent = new Intent(
                                        Intent.ActionMediaScannerScanFile);
                                    var contentUri = Android.Net.Uri.FromFile(App._file);
                                    mediaScanIntent.SetData(contentUri);
                                    this.SendBroadcast(mediaScanIntent);
                                }
                                else
                                {
                                    //SendBroadcast(new Intent(Intent.ActionMediaMounted, MediaStore.Images.Thumbnails.ExternalContentUri));
                                    SendBroadcast(new Intent(Intent.ActionMediaMounted, Android.Net.Uri.Parse("file://" + Android.OS.Environment.ExternalStorageDirectory)));
                                }
                            }

                            //GC.Collect ();
                        }catch (Exception ex) {
                            var toast = Toast.MakeText(ApplicationContext, ex.Message, ToastLength.Long);
                            toast.Show();
                        }
                    }
                }
            }catch (Exception ex) {
                var toast = Toast.MakeText(ApplicationContext, ex.Message, ToastLength.Long);
                toast.Show();
            }
        }
Example #56
0
        public static void ReadImageFileToTensor <T>(
            String fileName,
            IntPtr dest,
            int inputHeight     = -1,
            int inputWidth      = -1,
            float inputMean     = 0.0f,
            float scale         = 1.0f,
            bool flipUpSideDown = false,
            bool swapBR         = false)
            where T : struct
        {
#if __ANDROID__
            if (flipUpSideDown)
            {
                throw new NotImplementedException("Flip Up Side Down is Not implemented");
            }
            if (swapBR)
            {
                throw new NotImplementedException("swapBR is Not implemented");
            }
            Android.Graphics.Bitmap bmp = BitmapFactory.DecodeFile(fileName);

            if (inputHeight > 0 || inputWidth > 0)
            {
                Bitmap resized = Bitmap.CreateScaledBitmap(bmp, inputWidth, inputHeight, false);
                bmp.Dispose();
                bmp = resized;
            }
            int[]   intValues   = new int[bmp.Width * bmp.Height];
            float[] floatValues = new float[bmp.Width * bmp.Height * 3];
            bmp.GetPixels(intValues, 0, bmp.Width, 0, 0, bmp.Width, bmp.Height);
            for (int i = 0; i < intValues.Length; ++i)
            {
                int val = intValues[i];
                floatValues[i * 3 + 0] = (((val >> 16) & 0xFF) - inputMean) * scale;
                floatValues[i * 3 + 1] = (((val >> 8) & 0xFF) - inputMean) * scale;
                floatValues[i * 3 + 2] = ((val & 0xFF) - inputMean) * scale;
            }

            Marshal.Copy(floatValues, 0, dest, floatValues.Length);
#elif __IOS__
            if (flipUpSideDown)
            {
                throw new NotImplementedException("Flip Up Side Down is Not implemented");
            }
            if (swapBR)
            {
                throw new NotImplementedException("swapBR is Not implemented");
            }
            UIImage image = new UIImage(fileName);
            if (inputHeight > 0 || inputWidth > 0)
            {
                UIImage resized = image.Scale(new CGSize(inputWidth, inputHeight));
                image.Dispose();
                image = resized;
            }
            int[]   intValues   = new int[(int)(image.Size.Width * image.Size.Height)];
            float[] floatValues = new float[(int)(image.Size.Width * image.Size.Height * 3)];
            System.Runtime.InteropServices.GCHandle handle = System.Runtime.InteropServices.GCHandle.Alloc(intValues, System.Runtime.InteropServices.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();

            for (int i = 0; i < intValues.Length; ++i)
            {
                int val = intValues[i];
                floatValues[i * 3 + 0] = (((val >> 16) & 0xFF) - inputMean) * scale;
                floatValues[i * 3 + 1] = (((val >> 8) & 0xFF) - inputMean) * scale;
                floatValues[i * 3 + 2] = ((val & 0xFF) - inputMean) * scale;
            }
            System.Runtime.InteropServices.Marshal.Copy(floatValues, 0, dest, floatValues.Length);
#elif __UNIFIED__
            if (flipUpSideDown)
            {
                throw new NotImplementedException("Flip Up Side Down is Not implemented");
            }
            if (swapBR)
            {
                throw new NotImplementedException("swapBR is Not implemented");
            }
            NSImage image = new NSImage(fileName);
            if (inputHeight > 0 || inputWidth > 0)
            {
                NSImage resized = new NSImage(new CGSize(inputWidth, inputHeight));
                resized.LockFocus();
                image.DrawInRect(new CGRect(0, 0, inputWidth, inputHeight), CGRect.Empty, NSCompositingOperation.SourceOver, 1.0f);
                resized.UnlockFocus();
                image.Dispose();
                image = resized;
            }
            int[]   intValues   = new int[(int)(image.Size.Width * image.Size.Height)];
            float[] floatValues = new float[(int)(image.Size.Width * image.Size.Height * 3)];
            System.Runtime.InteropServices.GCHandle handle = System.Runtime.InteropServices.GCHandle.Alloc(intValues, System.Runtime.InteropServices.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();

            for (int i = 0; i < intValues.Length; ++i)
            {
                int val = intValues[i];
                floatValues[i * 3 + 0] = (((val >> 16) & 0xFF) - inputMean) * scale;
                floatValues[i * 3 + 1] = (((val >> 8) & 0xFF) - inputMean) * scale;
                floatValues[i * 3 + 2] = ((val & 0xFF) - inputMean) * scale;
            }
            System.Runtime.InteropServices.Marshal.Copy(floatValues, 0, dest, floatValues.Length);
#elif UNITY_EDITOR || UNITY_IOS || UNITY_ANDROID || UNITY_STANDALONE
            Texture2D texture = ReadTexture2DFromFile(fileName);
            ReadTensorFromTexture2D <T>(texture, dest, inputHeight, inputWidth, inputMean, scale, flipUpSideDown, false);
#else
            if (Emgu.TF.Util.Platform.OperationSystem == OS.Windows)
            {
                //Do something for Windows
                System.Drawing.Bitmap bmp = new Bitmap(fileName);

                if (inputHeight > 0 || inputWidth > 0)
                {
                    //resize bmp
                    System.Drawing.Bitmap newBmp = new Bitmap(bmp, inputWidth, inputHeight);
                    bmp.Dispose();
                    bmp = newBmp;
                    //bmp.Save("tmp.png");
                }

                if (flipUpSideDown)
                {
                    bmp.RotateFlip(RotateFlipType.RotateNoneFlipY);
                }

                byte[] byteValues = new byte[bmp.Width * bmp.Height * 3];
                System.Drawing.Imaging.BitmapData bd = new System.Drawing.Imaging.BitmapData();

                bmp.LockBits(
                    new Rectangle(0, 0, bmp.Width, bmp.Height),
                    System.Drawing.Imaging.ImageLockMode.ReadOnly,
                    System.Drawing.Imaging.PixelFormat.Format24bppRgb, bd);
                Marshal.Copy(bd.Scan0, byteValues, 0, byteValues.Length);
                bmp.UnlockBits(bd);

                if (typeof(T) == typeof(float))
                {
                    int     imageSize   = bmp.Width * bmp.Height;
                    float[] floatValues = new float[imageSize * 3];
                    if (swapBR)
                    {
                        for (int i = 0; i < imageSize; ++i)
                        {
                            floatValues[i * 3]     = (byte)(((float)byteValues[i * 3 + 2] - inputMean) * scale);
                            floatValues[i * 3 + 1] = (byte)(((float)byteValues[i * 3 + 1] - inputMean) * scale);
                            floatValues[i * 3 + 2] = (byte)(((float)byteValues[i * 3 + 0] - inputMean) * scale);
                        }
                    }
                    else
                    {
                        for (int i = 0; i < byteValues.Length; ++i)
                        {
                            floatValues[i] = ((float)byteValues[i] - inputMean) * scale;
                        }
                    }
                    Marshal.Copy(floatValues, 0, dest, floatValues.Length);
                }
                else if (typeof(T) == typeof(byte))
                {
                    if (swapBR)
                    {
                        int imageSize = bmp.Width * bmp.Height;
                        //byte[] bValues = new byte[imageSize * 3];
                        for (int i = 0; i < imageSize; ++i)
                        {
                            byte c0 = (byte)(((float)byteValues[i * 3 + 2] - inputMean) * scale);
                            byte c1 = (byte)(((float)byteValues[i * 3 + 1] - inputMean) * scale);
                            byte c2 = (byte)(((float)byteValues[i * 3 + 0] - inputMean) * scale);
                            byteValues[i * 3]     = c0;
                            byteValues[i * 3 + 1] = c1;
                            byteValues[i * 3 + 2] = c2;
                        }
                    }
                    else
                    {
                        if (!(inputMean == 0.0f && scale == 1.0f))
                        {
                            for (int i = 0; i < byteValues.Length; ++i)
                            {
                                byteValues[i] = (byte)(((float)byteValues[i] - inputMean) * scale);
                            }
                        }
                    }
                    Marshal.Copy(byteValues, 0, dest, byteValues.Length);
                }
                else
                {
                    throw new Exception(String.Format("Destination data type {0} is not supported.", typeof(T).ToString()));
                }
            }
            else //Unix
            {
                if (flipUpSideDown)
                {
                    throw new NotImplementedException("Flip Up Side Down is Not implemented");
                }

                throw new Exception("Not implemented");
            }
#endif
        }
            public MyAsyncTask(NiceArtEditor editor, string imagePath, NiceArtEditorView parentView, INiceArt.IOnSaveListener onSaveListener, SaveSettings saveSettings, Bitmap saveBitmap, SaveType type) : base()
            {
                try
                {
                    // do stuff
                    Editor         = editor;
                    ImagePath      = imagePath;
                    ParentView     = parentView;
                    OnSaveListener = onSaveListener;
                    Type           = type;
                    SaveSettings   = saveSettings;
                    SaveBitmap     = saveBitmap;

                    Editor?.ClearHelperBox();
                }
                catch (Exception e)
                {
                    Methods.DisplayReportResultTrack(e);
                }
            }
        // Called automatically whenever an activity finishes
        protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
        {
            base.OnActivityResult(requestCode, resultCode, data);
            SetContentView(Resource.Layout.PicManip);
            bool reverted = true;


            Button remred    = FindViewById <Button>(Resource.Id.RemRed);
            Button remgreen  = FindViewById <Button>(Resource.Id.RemGreen);
            Button remblue   = FindViewById <Button>(Resource.Id.RemBlue);
            Button negred    = FindViewById <Button>(Resource.Id.NegRed);
            Button neggreen  = FindViewById <Button>(Resource.Id.NegGreen);
            Button negblue   = FindViewById <Button>(Resource.Id.NegBlue);
            Button greyscale = FindViewById <Button>(Resource.Id.Greyscale);
            Button high_cont = FindViewById <Button>(Resource.Id.HighContrast);
            Button add_noise = FindViewById <Button>(Resource.Id.AddNoise);
            Button revert    = FindViewById <Button>(Resource.Id.Revert);
            Button save      = FindViewById <Button>(Resource.Id.Save);

            //test to make sure the picture was found
            if ((resultCode == Result.Ok) && (data != null))
            {
                //Make image available in the gallery
                //Test to see if we came from the camera or gallery
                //If we came from galley no need to make pic available
                if (requestCode == 0)
                {
                    Intent mediaScanIntent = new Intent(Intent.ActionMediaScannerScanFile);
                    var    contentUri      = Android.Net.Uri.FromFile(_file);
                    mediaScanIntent.SetData(contentUri);
                    SendBroadcast(mediaScanIntent);
                }
            }

            // Display in ImageView. We will resize the bitmap to fit the display.
            // Loading the full sized image will consume too much memory
            // and cause the application to crash.
            ImageView imageView = FindViewById <ImageView>(Resource.Id.takenPictureImageView);
            int       height    = Resources.DisplayMetrics.HeightPixels;
            int       width     = imageView.Height;

            bitmap = (Android.Graphics.Bitmap)data.Extras.Get("data");
            bitmap = Android.Graphics.Bitmap.CreateScaledBitmap(bitmap, 1024, 768, true);

            //check to make sure the bitmap has data we can manipulate
            if (bitmap != null)
            {
                copyBitmap = bitmap.Copy(Android.Graphics.Bitmap.Config.Argb8888, true);
                imageView.SetImageBitmap(copyBitmap);
            }

            else
            {
                //If bitmap is null takes the user back to the original screen
                StartMainLayout();
            }

            //Removes the red in the picture by setting the red pixel to 0
            remred.Click += delegate
            {
                for (int i = 0; i < copyBitmap.Width; i++)
                {
                    for (int j = 0; j < copyBitmap.Height; j++)
                    {
                        int p = copyBitmap.GetPixel(i, j);
                        Android.Graphics.Color c = new Android.Graphics.Color(p);

                        c.R = 0;
                        copyBitmap.SetPixel(i, j, c);
                    }
                }

                imageView.SetImageBitmap(copyBitmap);
                reverted = false;
            };

            //Removes the green in the picture by setting the green pixel to 0
            remgreen.Click += delegate
            {
                for (int i = 0; i < copyBitmap.Width; i++)
                {
                    for (int j = 0; j < copyBitmap.Height; j++)
                    {
                        int p = copyBitmap.GetPixel(i, j);
                        Android.Graphics.Color c = new Android.Graphics.Color(p);

                        c.G = 0;
                        copyBitmap.SetPixel(i, j, c);
                    }
                }

                imageView.SetImageBitmap(copyBitmap);
                reverted = false;
            };

            //Removes the blue in the picture by setting the blue pixel to 0
            remblue.Click += delegate
            {
                for (int i = 0; i < copyBitmap.Width; i++)
                {
                    for (int j = 0; j < copyBitmap.Height; j++)
                    {
                        int p = copyBitmap.GetPixel(i, j);
                        Android.Graphics.Color c = new Android.Graphics.Color(p);

                        c.B = 0;
                        copyBitmap.SetPixel(i, j, c);
                    }
                }

                imageView.SetImageBitmap(copyBitmap);
                reverted = false;
            };

            //Negates the red in the picture by subtracting 255 from the current red pixels value
            negred.Click += delegate
            {
                for (int i = 0; i < copyBitmap.Width; i++)
                {
                    for (int j = 0; j < copyBitmap.Height; j++)
                    {
                        int p = copyBitmap.GetPixel(i, j);
                        Android.Graphics.Color c = new Android.Graphics.Color(p);
                        int r1 = c.R;
                        r1  = 255 - r1;
                        c.R = Convert.ToByte(r1);
                        copyBitmap.SetPixel(i, j, c);
                    }
                }

                imageView.SetImageBitmap(copyBitmap);
                reverted = false;
            };

            //Negates the green in the picture by subtracting 255 from the current green pixels value
            neggreen.Click += delegate
            {
                for (int i = 0; i < copyBitmap.Width; i++)
                {
                    for (int j = 0; j < copyBitmap.Height; j++)
                    {
                        int p = copyBitmap.GetPixel(i, j);
                        Android.Graphics.Color c = new Android.Graphics.Color(p);
                        int g1 = c.G;
                        g1  = 255 - g1;
                        c.G = Convert.ToByte(g1);
                        copyBitmap.SetPixel(i, j, c);
                    }
                }

                imageView.SetImageBitmap(copyBitmap);
                reverted = false;
            };

            //Negates the blue in the picture by subtracting 255 from the current blue pixels value
            negblue.Click += delegate
            {
                for (int i = 0; i < copyBitmap.Width; i++)
                {
                    for (int j = 0; j < copyBitmap.Height; j++)
                    {
                        int p = copyBitmap.GetPixel(i, j);
                        Android.Graphics.Color c = new Android.Graphics.Color(p);
                        int b1 = c.B;
                        b1  = 255 - b1;
                        c.B = Convert.ToByte(b1);
                        copyBitmap.SetPixel(i, j, c);
                    }
                }

                imageView.SetImageBitmap(copyBitmap);
                reverted = false;
            };

            //Converts the picture to greyscale by averaging all the pixels values
            //Then setting the each pixel to the average
            greyscale.Click += delegate
            {
                for (int i = 0; i < copyBitmap.Width; i++)
                {
                    for (int j = 0; j < copyBitmap.Height; j++)
                    {
                        int average = 0;
                        int p       = copyBitmap.GetPixel(i, j);
                        Android.Graphics.Color c = new Android.Graphics.Color(p);
                        int r_temp = c.R;
                        int g_temp = c.G;
                        int b_temp = c.B;

                        average = (r_temp + g_temp + b_temp) / 3;

                        c.R = Convert.ToByte(average);
                        c.G = Convert.ToByte(average);
                        c.B = Convert.ToByte(average);
                        copyBitmap.SetPixel(i, j, c);
                    }
                }
                imageView.SetImageBitmap(copyBitmap);
                reverted = false;
            };

            //Converts the picture to high contrast
            //If the pixel > 127.5, then set to 255, else set to 0
            high_cont.Click += delegate
            {
                for (int i = 0; i < copyBitmap.Width; i++)
                {
                    for (int j = 0; j < copyBitmap.Height; j++)
                    {
                        int check_num            = 255 / 2;
                        int p                    = copyBitmap.GetPixel(i, j);
                        Android.Graphics.Color c = new Android.Graphics.Color(p);
                        int r_temp               = c.R;
                        int g_temp               = c.G;
                        int b_temp               = c.B;

                        if (r_temp > check_num)
                        {
                            r_temp = 255;
                        }

                        else
                        {
                            r_temp = 0;
                        }

                        if (g_temp > check_num)
                        {
                            g_temp = 255;
                        }

                        else
                        {
                            g_temp = 0;
                        }

                        if (b_temp > check_num)
                        {
                            b_temp = 255;
                        }

                        else
                        {
                            b_temp = 0;
                        }

                        c.R = Convert.ToByte(r_temp);
                        c.G = Convert.ToByte(g_temp);
                        c.B = Convert.ToByte(b_temp);
                        copyBitmap.SetPixel(i, j, c);
                    }
                }
                imageView.SetImageBitmap(copyBitmap);
                reverted = false;
            };

            //Adds random noise to the picture
            //Get a random value from -10 - 10, and add it to the pixels value
            //making sure the pixel value doesn't go over 255 or under 0.
            add_noise.Click += delegate
            {
                Random rnd = new Random();

                for (int i = 0; i < copyBitmap.Width; i++)
                {
                    for (int j = 0; j < copyBitmap.Height; j++)
                    {
                        int p = copyBitmap.GetPixel(i, j);
                        Android.Graphics.Color c = new Android.Graphics.Color(p);
                        int rand_val             = rnd.Next(-10, 11);
                        int r_temp = c.R;
                        int g_temp = c.G;
                        int b_temp = c.B;

                        r_temp += rand_val;
                        g_temp += rand_val;
                        b_temp += rand_val;

                        if (r_temp > 255)
                        {
                            r_temp = 255;
                        }
                        else if (r_temp < 0)
                        {
                            r_temp = 0;
                        }

                        if (g_temp > 255)
                        {
                            g_temp = 255;
                        }
                        else if (g_temp < 0)
                        {
                            g_temp = 0;
                        }

                        if (b_temp > 255)
                        {
                            b_temp = 255;
                        }
                        else if (b_temp < 0)
                        {
                            b_temp = 0;
                        }

                        c.R = Convert.ToByte(r_temp);
                        c.G = Convert.ToByte(g_temp);
                        c.B = Convert.ToByte(b_temp);
                        copyBitmap.SetPixel(i, j, c);
                    }
                }

                imageView.SetImageBitmap(copyBitmap);
                reverted = false;
            };

            //Button used to revert the image effects back to the orginal picture
            revert.Click += delegate
            {
                if (bitmap != null && !reverted)
                {
                    copyBitmap = bitmap.Copy(Android.Graphics.Bitmap.Config.Argb8888, true);
                    imageView.SetImageBitmap(copyBitmap);
                    reverted = true;
                }

                else if (reverted)
                {
                    Toast.MakeText(this, "The picture is the original.", ToastLength.Short).Show();
                }
            };

            //Saves the image to the users gallery
            save.Click += delegate
            {
                var sdCardPath = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath;
                var filePath   = System.IO.Path.Combine(sdCardPath, "ImageManip_{0}.png");
                var stream     = new FileStream(filePath, FileMode.Create);
                copyBitmap.Compress(Bitmap.CompressFormat.Png, 100, stream);
                stream.Close();
                Toast.MakeText(this, "The picture was saved to gallery.", ToastLength.Short).Show();

                StartMainLayout();
            };

            // Dispose of the Java side bitmap.
            System.GC.Collect();
        }
        public override void OnActivityResult(int requestCode, int resultCode, Intent data)
        {
            // if the result is capturing Image
            if ((requestCode == GALLERY_REQUEST_CODE1))
            {
                try
                {
                    Android.Net.Uri selectedImage  = data.Data;
                    string[]        filePathColumn = { MediaStore.Images.Media.InterfaceConsts.Data };

                    // Get the cursor
                    ICursor cursor = this.Activity.ContentResolver.Query(selectedImage, filePathColumn, null, null, null);
                    // Move to first row
                    cursor.MoveToFirst();

                    int    columnIndex        = cursor.GetColumnIndex(filePathColumn[0]);
                    string imgDecodableString = cursor.GetString(columnIndex);
                    cursor.Close();

                    //filePath = imgDecodableString;

                    Android.Graphics.Bitmap b       = BitmapFactory.DecodeFile(imgDecodableString);
                    Android.Graphics.Bitmap outputb = Android.Graphics.Bitmap.CreateScaledBitmap(b, 1200, 1024, false);

                    //getting image from gallery
                    bitmap = MediaStore.Images.Media.GetBitmap(this.Activity.ContentResolver, selectedImage);


                    Java.IO.File file = new Java.IO.File(imgDecodableString);
                    filePath = file.AbsolutePath;
                    FileStream fOut;
                    try
                    {
                        fOut = new FileStream(filePath, FileMode.Create);
                        outputb.Compress(Android.Graphics.Bitmap.CompressFormat.Jpeg, 80, fOut);
                        fOut.Flush();
                        fOut.Close();
                        //b.recycle();
                        //out.recycle();
                    }
                    catch (Java.Lang.Exception e)
                    {
                        e.PrintStackTrace();
                    }

                    if (requestCode == GALLERY_REQUEST_CODE1)
                    {
                        // Set the Image in ImageView after decoding the String
                        iv_profile.SetImageBitmap(bitmap);
                    }
                }
                catch (NullPointerException e)
                {
                    e.PrintStackTrace();
                }
                catch (Java.Lang.Exception e)
                {
                    e.PrintStackTrace();
                }
            }
        }
Example #60
0
        /// <summary>
        /// Read an image file, covert the data and save it to the native pointer
        /// </summary>
        /// <typeparam name="T">The type of the data to covert the image pixel values to. e.g. "float" or "byte"</typeparam>
        /// <param name="fileName">The name of the image file</param>
        /// <param name="dest">The native pointer where the image pixels values will be saved to.</param>
        /// <param name="inputHeight">The height of the image, must match the height requirement for the tensor</param>
        /// <param name="inputWidth">The width of the image, must match the width requirement for the tensor</param>
        /// <param name="inputMean">The mean value, it will be subtracted from the input image pixel values</param>
        /// <param name="scale">The scale, after mean is subtracted, the scale will be used to multiply the pixel values</param>
        /// <param name="flipUpSideDown">If true, the image needs to be flipped up side down</param>
        /// <param name="swapBR">If true, will flip the Blue channel with the Red. e.g. If false, the tensor's color channel order will be RGB. If true, the tensor's color channle order will be BGR </param>
        public static void ReadImageFileToTensor <T>(
            String fileName,
            IntPtr dest,
            int inputHeight     = -1,
            int inputWidth      = -1,
            float inputMean     = 0.0f,
            float scale         = 1.0f,
            bool flipUpSideDown = false,
            bool swapBR         = false)
            where T : struct
        {
            if (!File.Exists(fileName))
            {
                throw new FileNotFoundException(String.Format("File {0} do not exist.", fileName));
            }

            Android.Graphics.Bitmap bmp = BitmapFactory.DecodeFile(fileName);
            if (inputHeight > 0 || inputWidth > 0)
            {
                Bitmap resized = Bitmap.CreateScaledBitmap(bmp, inputWidth, inputHeight, false);
                bmp.Dispose();
                bmp = resized;
            }

            if (flipUpSideDown)
            {
                Matrix matrix = new Matrix();
                matrix.PostScale(1, -1, bmp.Width / 2, bmp.Height / 2);
                Bitmap flipped = Bitmap.CreateBitmap(bmp, 0, 0, bmp.Width, bmp.Height, matrix, true);
                bmp.Dispose();
                bmp = flipped;
            }

            int[]   intValues   = new int[bmp.Width * bmp.Height];
            float[] floatValues = new float[bmp.Width * bmp.Height * 3];
            bmp.GetPixels(intValues, 0, bmp.Width, 0, 0, bmp.Width, bmp.Height);

            if (swapBR)
            {
                for (int i = 0; i < intValues.Length; ++i)
                {
                    int val = intValues[i];
                    floatValues[i * 3 + 0] = ((val & 0xFF) - inputMean) * scale;
                    floatValues[i * 3 + 1] = (((val >> 8) & 0xFF) - inputMean) * scale;
                    floatValues[i * 3 + 2] = (((val >> 16) & 0xFF) - inputMean) * scale;
                }
            }
            else
            {
                for (int i = 0; i < intValues.Length; ++i)
                {
                    int val = intValues[i];
                    floatValues[i * 3 + 0] = (((val >> 16) & 0xFF) - inputMean) * scale;
                    floatValues[i * 3 + 1] = (((val >> 8) & 0xFF) - inputMean) * scale;
                    floatValues[i * 3 + 2] = ((val & 0xFF) - inputMean) * scale;
                }
            }

            if (typeof(T) == typeof(float))
            {
                Marshal.Copy(floatValues, 0, dest, floatValues.Length);
            }
            else if (typeof(T) == typeof(byte))
            {
                //copy float to bytes
                byte[] byteValues = new byte[floatValues.Length];
                for (int i = 0; i < floatValues.Length; i++)
                {
                    byteValues[i] = (byte)floatValues[i];
                }
                Marshal.Copy(byteValues, 0, dest, byteValues.Length);
            }
            else
            {
                throw new NotImplementedException(String.Format("Destination data type {0} is not supported.", typeof(T).ToString()));
            }
        }