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; } }
/// <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; }
public static String BitmapToBase64String(Bitmap originalImage) { MemoryStream ms = new MemoryStream(); originalImage.Compress(Bitmap.CompressFormat.Png, 100, ms); byte[] imageData = ms.ToArray(); originalImage.Dispose(); return Base64.EncodeToString(imageData, Base64Flags.NoWrap); }
static private byte[] getBytes(Bitmap b) { using (var stream = new MemoryStream()) { b.Compress(Bitmap.CompressFormat.Png, 0, stream); return stream.ToArray(); } }
public static void WriteBmp( Bitmap bmp, Stream dst ) { #if !ANDROID bmp.Save( dst, ImageFormat.Png ); #else bmp.Compress( Bitmap.CompressFormat.Png, 100, dst ); #endif }
public static byte[] ByteArrayFromImage(Bitmap bmp) { using (var stream = new MemoryStream()) { bmp.Compress(Bitmap.CompressFormat.Png, 0, stream); return stream.ToArray(); } }
public static DumpValue AsImage(Bitmap image) { byte[] dataBytes; using (var stream = new MemoryStream()) { image.Compress(Bitmap.CompressFormat.Jpeg, 60, stream); dataBytes = stream.ToArray(); } return new DumpValue { TypeName = "___IMAGE___", DumpType = DumpValue.DumpTypes.Image, PrimitiveValue = Convert.ToBase64String(dataBytes) }; }
public static byte[] ImagetoByteArray(Android.Graphics.Bitmap bitmap, int quality = 90) { byte[] bitmapData; using (var stream = new MemoryStream()) { bitmap.Compress(Android.Graphics.Bitmap.CompressFormat.Jpeg, quality, stream); bitmapData = stream.ToArray(); } return(bitmapData); }
private File SaveBitmap(Bitmap b) { string filename = string.Format("{0}MyFile{1:HH_mm_s}.jpg", DIRECTORY_PATH, DateTime.Now); File f = new File(filename); using (System.IO.FileStream fs = new System.IO.FileStream(f.AbsolutePath, System.IO.FileMode.OpenOrCreate)) { b.Compress(Bitmap.CompressFormat.Jpeg, 9, fs); return f; } }
public static byte[] BitmapToBytes(Android.Graphics.Bitmap bitmap) { byte[] data = new byte[0]; using (System.IO.MemoryStream stream = new System.IO.MemoryStream()) { bitmap.Compress(Android.Graphics.Bitmap.CompressFormat.Jpeg, 90, stream); stream.Close(); data = stream.ToArray(); } return(data); }
/// <summary> /// Convert bitmap to jpeg /// </summary> /// <param name="bmp">The android bitmap</param> /// <returns>The jpeg representation</returns> public static Emgu.Models.JpegData ToJpeg(this Android.Graphics.Bitmap bmp) { using (MemoryStream ms = new MemoryStream()) { bmp.Compress(Bitmap.CompressFormat.Jpeg, 90, ms); JpegData result = new JpegData(); result.Raw = ms.ToArray(); result.Width = bmp.Width; result.Height = bmp.Height; return(result); } }
public void SaveToStream(Stream stream, ImageFileType fileType) { if (Image == null) { return; } if (fileType == ImageFileType.Bmp) { throw new ArgumentException(string.Format("{0} is not supported", fileType)); } Image.Compress(fileType.ToDroid(), 100, stream); }
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); } }
public static string ImageToBase64(Android.Graphics.Bitmap image, int quality = 90) { var stream = new System.IO.MemoryStream(); //using () //{ image.Compress(Android.Graphics.Bitmap.CompressFormat.Jpeg, quality, stream); //float mb = (stream.ToArray().Length / 1024f) / 1024f; return(Convert.ToBase64String(stream.ToArray())); //} }
// changer le format des images public string ResizeImage(string sourceFilePath) { Android.Graphics.Bitmap bmp = Android.Graphics.BitmapFactory.DecodeFile(sourceFilePath); string newPath = sourceFilePath.Replace(".jpg", ".png"); using (var fs = new FileStream(newPath, FileMode.OpenOrCreate)) { bmp.Compress(Android.Graphics.Bitmap.CompressFormat.Png, 100, fs); } return(newPath); }
private MemoryStream RenderToBitmapStreamPrivate(IViewport viewport, IEnumerable <ILayer> layers) { Bitmap target = Bitmap.CreateBitmap((int)viewport.Width, (int)viewport.Height, Bitmap.Config.Argb8888); var canvas = new Canvas(target); Render(canvas, viewport, layers, ShowDebugInfoInMap); var stream = new MemoryStream(); target.Compress(Bitmap.CompressFormat.Png, 100, stream); target.Dispose(); canvas.Dispose(); return(stream); }
private async void SetMetaData(int position, string title, string artist, ThumbnailSet thumbnails) { string filePath = queue[position].Path; await Task.Run(async() => { Stream stream = new FileStream(filePath, FileMode.Open, FileAccess.ReadWrite); var meta = TagLib.File.Create(new StreamFileAbstraction(filePath, stream, stream)); meta.Tag.Title = title; meta.Tag.Performers = new string[] { artist }; meta.Tag.Album = title + " - " + artist; meta.Tag.Comment = queue[position].YoutubeID; IPicture[] pictures = new IPicture[1]; Bitmap bitmap = Picasso.With(this).Load(await YoutubeManager.GetBestThumb(thumbnails)).Transform(new RemoveBlackBorder(true)).MemoryPolicy(MemoryPolicy.NoCache).Get(); byte[] data; using (var MemoryStream = new MemoryStream()) { bitmap.Compress(Bitmap.CompressFormat.Png, 0, MemoryStream); data = MemoryStream.ToArray(); } bitmap.Recycle(); pictures[0] = new Picture(data); meta.Tag.Pictures = pictures; meta.Save(); stream.Dispose(); }); MediaScannerConnection.ScanFile(this, new string[] { filePath }, null, this); if (queue[position].PlaylistName == null) { queue[position].State = DownloadState.Completed; } else { queue[position].State = DownloadState.Playlist; } if (!queue.Exists(x => x.State == DownloadState.None || x.State == DownloadState.Downloading || x.State == DownloadState.Initialization || x.State == DownloadState.MetaData || x.State == DownloadState.Playlist)) { StopForeground(true); DownloadQueue.instance?.Finish(); queue.Clear(); } else { UpdateList(position); } }
public async Task<string> UploadImage(Bitmap bitmap) { var uploadVM = new UploadViewModel(); var stream = new MemoryStream(); bitmap.Compress(Bitmap.CompressFormat.Png, 0, stream); uploadVM.PictureStream = stream; uploadVM.ImageIdentifier = Guid.NewGuid() + ".bmp"; await azureStorageService.UploadPicture(uploadVM); return string.Format("{0}{1}", AndroidPollImageViewModel.PollPicturesUrlBase, uploadVM.ImageIdentifier); }
public static string ResizeImage(string sourceFilePath) { string newPath = sourceFilePath.Replace(".jpg", "_.jpg"); newPath = System.IO.Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), System.IO.Path.GetFileName(newPath)); using (Android.Graphics.Bitmap bmp = Android.Graphics.BitmapFactory.DecodeFile(sourceFilePath)) { using (var fs = new FileStream(newPath, FileMode.OpenOrCreate)) { bmp.Compress(Android.Graphics.Bitmap.CompressFormat.Jpeg, 20, fs); } } GC.Collect(); return(newPath); }
private void BtnSave_Click(object sender, EventArgs e) { SignatureImage = sign_pad.GetImage(); //byte[] b = new byte[(long)f.Length()]; //f.ReadFully(b); //Java.IO.File file; //Toast.MakeText(Activity, "Signature Saved", ToastLength.Short).Show(); //ByteBuffer buffer = ByteBuffer.Allocate(SignatureImage.ByteCount); //SignatureImage.CopyPixelsToBuffer(buffer); //buffer.Rewind(); ////Byte array signature //IntPtr classHandle = JNIEnv.FindClass("java/nio/ByteBuffer"); //IntPtr methodId = JNIEnv.GetMethodID(classHandle, "array", "()[B"); //IntPtr resultHandle = JNIEnv.CallObjectMethod(buffer.Handle, methodId); //byte[] result = JNIEnv.GetArray<byte>(resultHandle); //JNIEnv.DeleteLocalRef(resultHandle); try { int byteSize = SignatureImage.RowBytes * SignatureImage.Height; int bytes = SignatureImage.ByteCount; MemoryStream stream = new MemoryStream(); SignatureImage.Compress(Bitmap.CompressFormat.Png, 0, stream); byte[] bitmapData = stream.ToArray(); bool uploadsign = SQL_Functions.uploadSignature(bitmapData); Toast.MakeText(Activity, "Signature Uploaded", ToastLength.Short).Show(); } catch (Exception ex) { new Android.Support.V7.App.AlertDialog.Builder(Activity).SetTitle("Indigent App Error").SetMessage("Upload failed: " + ex.Message + "\n \nPlease try again later").SetCancelable(true).Show(); } Dismiss(); }
public void Save(System.IO.Stream stream, Imaging.ImageCodecInfo info, Imaging.EncoderParameters e) { Android.Graphics.Bitmap.CompressFormat _format; switch (info.FormatDescription) { case "PNG": _format = Android.Graphics.Bitmap.CompressFormat.Png; break; case "JPEG": default: _format = Android.Graphics.Bitmap.CompressFormat.Jpeg; break; } ABitmap.Compress(_format, 100, stream); }
public byte[] DrawResultsToJpeg(String fileName, MultiboxGraph.Result detectResult, float scoreThreshold = 0.2f) { #if __ANDROID__ BitmapFactory.Options options = new BitmapFactory.Options(); options.InMutable = true; Android.Graphics.Bitmap bmp = BitmapFactory.DecodeFile(fileName, options); MultiboxGraph.DrawResults(bmp, detectResult, scoreThreshold); using (MemoryStream ms = new MemoryStream()) { bmp.Compress(Bitmap.CompressFormat.Jpeg, 90, ms); return(ms.ToArray()); } #elif __MACOS__ NSImage img = NSImage.ImageNamed(fileName); MultiboxGraph.DrawResults(img, detectResult, scoreThreshold); 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); UIImage newImg = MultiboxGraph.DrawResults(uiimage, detectResult, scoreThreshold); var jpegData = newImg.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); MultiboxGraph.DrawResults(img, detectResult, scoreThreshold); 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 }
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data) { base.OnActivityResult(requestCode, resultCode, data); if (resultCode == Result.Ok) { pic.SetImageURI(data.Data); Android.Graphics.Bitmap mBitmap = null; mBitmap = Android.Provider.MediaStore.Images.Media.GetBitmap(this.ContentResolver, data.Data); using (var stream = new MemoryStream()) { mBitmap.Compress(Bitmap.CompressFormat.Png, 0, stream); slika = stream.ToArray(); } } }
//TODO: ASync private void CallCloudVision(Android.Graphics.Bitmap bitmap) { mImageDetails.SetText(Resource.String.loading_message); GoogleCredential credential = GoogleCredential.GetApplicationDefaultAsync().Result; if (credential.IsCreateScopedRequired) { credential = credential.CreateScoped(new[] { VisionService.Scope.CloudPlatform }); } var vision = new VisionService(new BaseClientService.Initializer { HttpClientInitializer = credential, GZipEnabled = false }); var byteArrayOutputStream = new MemoryStream(); bitmap.Compress(Bitmap.CompressFormat.Png, 100, byteArrayOutputStream); var byteArray = byteArrayOutputStream.ToArray(); var imageData = Convert.ToBase64String(byteArray); var responses = vision.Images.Annotate( new BatchAnnotateImagesRequest() { Requests = new[] { new AnnotateImageRequest() { Features = new [] { new Feature() { Type = "LABEL_DETECTION" } }, Image = new Image() { Content = imageData } } } }).Execute(); }
/// <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 labels</param> /// <returns>The image in Jpeg stream format</returns> public static Emgu.Models.JpegData ImageFileToJpeg(String fileName, Annotation[] annotations = null) { using (BitmapFactory.Options options = new BitmapFactory.Options()) { options.InMutable = true; using (Android.Graphics.Bitmap bmp = BitmapFactory.DecodeFile(fileName, options)) { if (annotations != null) { using (Android.Graphics.Paint p = new Android.Graphics.Paint()) using (Canvas c = new Canvas(bmp)) { p.AntiAlias = true; p.Color = Android.Graphics.Color.Red; p.TextSize = 20; for (int i = 0; i < annotations.Length; i++) { p.SetStyle(Paint.Style.Stroke); 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); p.SetStyle(Paint.Style.Fill); c.DrawText(annotations[i].Label, (int)rects[0], (int)rects[1], p); } } } using (MemoryStream ms = new MemoryStream()) { bmp.Compress(Bitmap.CompressFormat.Jpeg, 90, ms); JpegData result = new JpegData(); result.Raw = ms.ToArray(); result.Width = bmp.Width; result.Height = bmp.Height; return(result); } } } }
public static void WriteToFile(Bitmap bitmap) { try { var outFile = new MemoryStream(); bitmap.Compress(Bitmap.CompressFormat.Png, 90, outFile); outFile.Position = 0; var path = Path.Combine("/sdcard/Download", "test.png"); var otherPath = Path.Combine(Application.Context.GetExternalFilesDir("unit_test_images").AbsolutePath, "test.png"); var fos = new FileStream(otherPath, FileMode.OpenOrCreate); fos.Write(outFile.ToArray(), 0, (int)outFile.Length); fos.Flush(); fos.Close(); } catch (Exception) { Console.WriteLine("fout!"); } }
protected override string RunInBackground(string[] str) { try { // Create a media file name Java.IO.File file = new Java.IO.File(ImagePath); try { var stream = new FileStream(file.Path, FileMode.Create); if (ParentView != null) { if (SaveSettings.IsTransparencyEnabled()) { Bitmap drawingCache = BitmapUtil.LoadBitmapFromView(ParentView); drawingCache.Compress(Bitmap.CompressFormat.Png, 100, stream); SavedResultBitmap = drawingCache; } else { return(""); } } stream.Flush(); stream.Close(); Console.WriteLine(Tag, "Filed Saved Successfully"); return(""); } catch (FileNotFoundException ex) { Methods.DisplayReportResultTrack(ex); //ex.PrintStackTrace(); Console.WriteLine(Tag, "Failed to save File"); return(ex.Message); } } catch (Exception e) { Methods.DisplayReportResultTrack(e); return(e.Message); } }
public async Task<bool> SaveImage(ImageSource img, string imageName) { try { var renderer = new StreamImagesourceHandler(); imagem = await renderer.LoadImageAsync(img, Forms.Context); var documentsDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal); string pngPath = System.IO.Path.Combine(documentsDirectory, imageName + ".png"); using (System.IO.FileStream fs = new System.IO.FileStream(pngPath, System.IO.FileMode.OpenOrCreate)) { imagem.Compress(Bitmap.CompressFormat.Png, 100, fs); return await Task.FromResult<bool>(true); } } catch (Exception) { return await Task.FromResult<bool>(false); } }
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()); } } }
/// <summary> /// Detect faces from a bitmap, and directly mark information on this bitmao /// </summary> /// <param name="originalBitmap"></param> /// <returns></returns> private static async Task<Bitmap> detectFacesAndMarkThem(Bitmap originalBitmap) { FaceServiceClient client = new FaceServiceClient(FaceAPIKey); MemoryStream stream = new MemoryStream(); originalBitmap.Compress(Bitmap.CompressFormat.Jpeg, imageQuality, stream); Face[] faces = await client.DetectAsync(stream.ToArray()); Bitmap resultBitmap = drawFaceRectanglesOnBitmap(originalBitmap, faces); return resultBitmap; }
void ExportBitmapAsJpg(Bitmap bitmap, string path) { var stream = new FileStream(path, System.IO.FileMode.Create); bitmap.Compress(Bitmap.CompressFormat.Jpeg, 100, stream); stream.Close(); }
protected override async void OnActivityResult(int requestCode, Result resultCode, Intent data) { base.OnActivityResult(requestCode, resultCode, data); try { //Get the bitmap with the right rotation _bitmap = BitmapHelpers.GetAndRotateBitmap(_file.Path); //Resize the picture to be under 4MB (Emotion API limitation and better for Android memory) _bitmap = Bitmap.CreateScaledBitmap(_bitmap, 2000, (int)(2000*_bitmap.Height/_bitmap.Width), false); //Display the image _imageView.SetImageBitmap(_bitmap); using (System.IO.MemoryStream stream = new System.IO.MemoryStream()) { //Get a stream _bitmap.Compress(Bitmap.CompressFormat.Jpeg, 90, stream); stream.Seek(0, System.IO.SeekOrigin.Begin); //Get and display the happiness score float result = await Core.GetAverageHappinessScore(stream); _resultTextView.Text = Core.GetHappinessMessage(result); } } catch (Exception ex) { _resultTextView.Text = ex.Message; } finally { _pictureButton.Text = "Reset"; _isCaptureMode = false; } }
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(); } }
private void saveOutput(Bitmap croppedImage) { if (saveUri != null) { try { using (var outputStream = ContentResolver.OpenOutputStream(saveUri)) { if (outputStream != null) { croppedImage.Compress(outputFormat, 75, outputStream); } } } catch (Exception ex) { Log.Error(this.GetType().Name, ex.Message); } Bundle extras = new Bundle(); SetResult(Result.Ok, new Intent(saveUri.ToString()) .PutExtras(extras)); } else { Log.Error(this.GetType().Name, "not defined image url"); } croppedImage.Recycle(); Finish(); }
/// <summary> /// Writes the bitmap to cache. /// </summary> /// <param name="bitmap">Current bitmap.</param> /// <param name="position">Position.</param> private void WriteBitmapToCache(Bitmap bitmap, int position) { if (bitmap != null) { try { using (Stream outputStream = File.Create(this.GetCacheFileName(position))) { // tune it for better results bitmap.Compress(Bitmap.CompressFormat.Png, 90, outputStream); } } catch (Exception e) { Console.WriteLine(e.Message); } } }
public static byte[] ImageToByte2(Bitmap bitmap) { /* Log.Debug ("ImageToByte", "Inicia Funcion Alternativa"); byte[] bitmapData; //Java.IO.File tf = new Java.IO.File (bitmap); return bitmapData; Log.Debug ("ImageToByte", "Termina Funcion Alternativa"); */ byte[] bitmapData; using (var stream = new MemoryStream()) { Log.Debug ("ImageToByte", "Inicia compressformat"); bitmap.Compress(Bitmap.CompressFormat.Jpeg, 70, stream); Log.Debug ("ImageToByte", "Inicia stream to array"); bitmapData = stream.ToArray(); Log.Debug ("ImageToByte", "Inicia stream dispose"); stream.Dispose (); Log.Debug ("ImageToByte", "Termina Método"); } return bitmapData; }
public static byte[] ImageToByte2(Bitmap bitmap) { byte[] bitmapData; using (var stream = new MemoryStream()) { Log.Debug ("ImageToByte", "Inicia compressformat"); bitmap.Compress(Bitmap.CompressFormat.Jpeg, 70, stream); Log.Debug ("ImageToByte", "Inicia stream to array"); bitmapData = stream.ToArray(); Log.Debug ("ImageToByte", "Inicia stream dispose"); stream.Dispose (); Log.Debug ("ImageToByte", "Termina Método"); } return bitmapData; }
public MultiboxDetectionPage() : base() { var button = this.GetButton(); button.Text = "Perform People Detection"; button.Clicked += OnButtonClicked; OnImagesLoaded += async(sender, image) => { GetLabel().Text = "Please wait..."; SetImage(); Task <Tuple <byte[], long> > t = new Task <Tuple <byte[], long> >( () => { //MultiboxGrapho.Download(); MultiboxGraph graph = new MultiboxGraph(); Tensor imageTensor = Emgu.TF.Models.ImageIO.ReadTensorFromImageFile(image[0], 224, 224, 128.0f, 1.0f / 128.0f); MultiboxGraph.Result detectResult = graph.Detect(imageTensor); #if __ANDROID__ BitmapFactory.Options options = new BitmapFactory.Options(); options.InMutable = true; Android.Graphics.Bitmap bmp = BitmapFactory.DecodeFile(image[0], options); MultiboxGraph.DrawResults(bmp, detectResult, 0.2f); using (MemoryStream ms = new MemoryStream()) { bmp.Compress(Bitmap.CompressFormat.Jpeg, 90, ms); return(new Tuple <byte[], long>(ms.ToArray(), 0)); } #elif __UNIFIED__ && !__IOS__ NSImage img = NSImage.ImageNamed(image[0]); Xamarin.Forms.Device.BeginInvokeOnMainThread(() => { MultiboxGraph.DrawResults(img, detectResult, 0.1f); var imageData = img.AsTiff(); var imageRep = NSBitmapImageRep.ImageRepsWithData(imageData)[0] as NSBitmapImageRep; var jpegData = imageRep.RepresentationUsingTypeProperties(NSBitmapImageFileType.Jpeg, null); byte[] raw = new byte[jpegData.Length]; System.Runtime.InteropServices.Marshal.Copy(jpegData.Bytes, raw, 0, (int)jpegData.Length); SetImage(raw); GetLabel().Text = String.Format("Detected with in {0} milliseconds.", 0); }); return(new Tuple <byte[], long>(null, 0)); #elif __IOS__ UIImage uiimage = new UIImage(image[0]); Xamarin.Forms.Device.BeginInvokeOnMainThread(() => { UIImage newImg = MultiboxGraph.DrawResults(uiimage, detectResult, 0.1f); var jpegData = newImg.AsJPEG(); byte[] raw = new byte[jpegData.Length]; System.Runtime.InteropServices.Marshal.Copy(jpegData.Bytes, raw, 0, (int)jpegData.Length); SetImage(raw); GetLabel().Text = String.Format("Detected with in {0} milliseconds.", 0); }); return(new Tuple <byte[], long>(null, 0)); #else return(new Tuple <byte[], long>(new byte[10], 0)); #endif }); t.Start(); #if !(__UNIFIED__) var result = await t; SetImage(t.Result.Item1); GetLabel().Text = String.Format("Detected with in {0} milliseconds.", t.Result.Item2); #endif }; }
private static void ExportBitmapAsPNG(Bitmap bitmap) { var sdCardPath = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath; var filePath = System.IO.Path.Combine(sdCardPath, "test"+fileCounter.ToString()+".png"); var stream = new FileStream(filePath, FileMode.Create); bitmap.Compress(Bitmap.CompressFormat.Png, 100, stream); stream.Close(); fileCounter++; }
/// <summary> /// Saves the cropped image /// </summary> /// <param name="croppedImage">the cropped image</param> /// <param name="saveUri"> the uri to save the cropped image to</param> internal void SaveOutput(Bitmap croppedImage, Android.Net.Uri saveUri) { if (saveUri == null) { Log.Error(this.GetType().Name, "invalid image url"); return; } using (var outputStream = context.ContentResolver.OpenOutputStream(saveUri)) { if (outputStream != null) { croppedImage.Compress(outputFormat, 75, outputStream); } } croppedImage.Recycle(); }
// 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(); }
private String HttpUploadFile(string url, Bitmap img, string paramName, string contentType, NameValueCollection nvc) { string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x"); byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n"); HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url); wr.ContentType = "multipart/form-data; boundary=" + boundary; wr.Method = "POST"; wr.KeepAlive = true; wr.Credentials = CredentialCache.DefaultCredentials; Stream rs = wr.GetRequestStream(); string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}"; foreach (string key in nvc.Keys) { rs.Write(boundarybytes, 0, boundarybytes.Length); string formitem = string.Format(formdataTemplate, key, nvc[key]); byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem); rs.Write(formitembytes, 0, formitembytes.Length); } rs.Write(boundarybytes, 0, boundarybytes.Length); string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n"; string header = string.Format(headerTemplate, paramName, Guid.NewGuid() + ".png", contentType); byte[] headerbytes = Encoding.UTF8.GetBytes(header); rs.Write(headerbytes, 0, headerbytes.Length); img.Compress (Bitmap.CompressFormat.Png, 100, rs); byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n"); rs.Write(trailer, 0, trailer.Length); rs.Close(); WebResponse wresp = null; try { wresp = wr.GetResponse(); Stream stream2 = wresp.GetResponseStream(); StreamReader reader2 = new StreamReader(stream2); return reader2.ReadToEnd(); } catch (Exception ex) { if (wresp != null) { wresp.Close(); wresp = null; } return null; } finally { wr = null; } }
public void downloadImage() { try { Uri uriBing = new Uri("http://cn.bing.com/HPImageArchive.aspx?idx=0&n=1"); WebRequest webRequest = WebRequest.Create(uriBing); WebResponse webResponse = webRequest.GetResponse(); Stream stream = webResponse.GetResponseStream(); XmlDocument xmldoc = new XmlDocument(); xmldoc.Load(stream); string picturePath = Application.Context.GetExternalFilesDir(Android.OS.Environment.DirectoryDownloads).AbsolutePath; string wallpaperSavePath = Application.Context.GetExternalFilesDir(Android.OS.Environment.DirectoryDownloads).AbsolutePath; //check folder if (!Directory.Exists(wallpaperSavePath)) { Directory.CreateDirectory(wallpaperSavePath); } else { //delete older files try { var files = Directory.EnumerateFiles("/storage/emulated/0/Android/data/lk.stechbuzz.bingwallpaper/files/"); if (files.Count() > 60) { string[] f = Directory.GetFiles("/storage/emulated/0/Android/data/lk.stechbuzz.bingwallpaper/files/"); foreach (var item in f) { File.SetAttributes(item, FileAttributes.Normal); File.Delete(item); } } } catch (Exception) { } } string fullStartDate = (xmldoc["images"]["image"]["fullstartdate"].InnerText); string urlBase = xmldoc["images"]["image"]["urlBase"].InnerText; string curImagePath = wallpaperSavePath + fullStartDate + ".jpg"; if (File.Exists(curImagePath)) { } else { string downloadUrl = "http://www.bing.com" + urlBase + "_1920x1080.jpg"; WebClient webClient = new WebClient(); try { webClient.DownloadFile(downloadUrl, @curImagePath); WallpaperManager wallpaperManager = WallpaperManager.GetInstance(Application.Context); if (Xamarin.Essentials.Preferences.Get("EnableAutoWallpaper", false)) { Android.Graphics.Bitmap rowBitmap = BitmapFactory.DecodeFile(curImagePath); Android.Graphics.Bitmap CroppedBitmap = Android.Graphics.Bitmap.CreateScaledBitmap(rowBitmap, wallpaperManager.DesiredMinimumWidth, wallpaperManager.DesiredMinimumWidth, true); Android.Graphics.Bitmap decoded = null; using (MemoryStream memory = new MemoryStream()) { CroppedBitmap.Compress(Android.Graphics.Bitmap.CompressFormat.Png, 100, memory); memory.Position = 0; decoded = Android.Graphics.BitmapFactory.DecodeStream(memory); memory.Flush(); } if (Xamarin.Essentials.Preferences.Get("Screen", 1) == 1) { wallpaperManager.SetBitmap(decoded, null, true, WallpaperManagerFlags.System); } else if (Xamarin.Essentials.Preferences.Get("Screen", 1) == 2) { wallpaperManager.SetBitmap(decoded, null, true, WallpaperManagerFlags.Lock); } else if (Xamarin.Essentials.Preferences.Get("Screen", 1) == 3) { wallpaperManager.SetBitmap(decoded, null, true, WallpaperManagerFlags.System); wallpaperManager.SetBitmap(decoded, null, true, WallpaperManagerFlags.Lock); } else { wallpaperManager.SetBitmap(decoded, null, true, WallpaperManagerFlags.System); } } } catch (Exception e) { Console.WriteLine(e.Message); } } } catch (Exception) { return; } }
/// <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 JpegData 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); JpegData result = new JpegData(); result.Raw = ms.ToArray(); result.Width = bmp.Width; result.Height = bmp.Height; return(result); } #elif __MACOS__ NSImage img = NSImage.ImageNamed(fileName); if (annotations != null && annotations.Length > 0) { DrawAnnotations(img, annotations); } 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); JpegData result = new JpegData(); result.Raw = jpeg; result.Width = (int)img.Size.Width; result.Height = (int)img.Size.Height; return(result); #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); } context.ScaleCTM(1, -1); context.TranslateCTM(0, -uiimage.Size.Height); for (int i = 0; i < annotations.Length; i++) { float[] rects = ScaleLocation( annotations[i].Rectangle, (int)uiimage.Size.Width, (int)uiimage.Size.Height); context.SelectFont("Helvetica", 18, CGTextEncoding.MacRoman); context.SetFillColor((nfloat)1.0, (nfloat)0.0, (nfloat)0.0, (nfloat)1.0); context.SetTextDrawingMode(CGTextDrawingMode.Fill); context.ShowTextAtPoint(rects[0], uiimage.Size.Height - rects[1], annotations[i].Label); } 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); JpegData result = new JpegData(); result.Raw = jpeg; result.Width = (int)uiimage.Size.Width; result.Height = (int)uiimage.Size.Height; return(result); #else 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(origin, new SizeF(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); JpegData result = new JpegData(); result.Raw = ms.ToArray(); result.Width = img.Size.Width; result.Height = img.Size.Height; return(result); } #endif }
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data) { base.OnActivityResult(requestCode, resultCode, data); if (resultCode == Result.Ok) { if (requestCode == 2) { try { Android.Net.Uri selectImage = data.Data; bitmapDetalle = null; imageurl = getRealPathFromURI(data.Data); imageurlId = data.Data.LastPathSegment; datetime = System.IO.File.GetLastAccessTimeUtc(imageurl); string fechahora = datetime.Day.ToString() + datetime.Month.ToString() + datetime.Year.ToString().Substring(2, 2) + "-" + datetime.Hour.ToString() + datetime.Minute.ToString(); GC.Collect(); if (File.Exists(imageurl)) { Android.Graphics.Bitmap bitmap = Utils.ChangeSizeBitmap(BitmapFactory.DecodeFile(imageurl), 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 { lblInfoFoto.Text = ODTDet.Folio + " - Evidencia - " + 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) { if (App._file.Exists()) { Intent mediaScannerIntent = new Intent(Intent.ActionMediaScannerScanFile); Android.Net.Uri contentUri = Android.Net.Uri.FromFile(App._file); mediaScannerIntent.SetData(contentUri); this.SendBroadcast(mediaScannerIntent); GC.Collect(); } } } }
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { RelativeLayout view = (RelativeLayout)inflater.Inflate(Resource.Layout.PostActivity, container, false); view.Click += (sender, e) => { ViewUtils.HideKeyboard(Activity, CaptionTextView); TabHostActivity.GetTabHost().ShowTabs(); }; Suggestions = view.FindViewById<SuggestionsLayout>(Resource.Id.suggestionsLayout); Suggestions.InitView(); Suggestions.UserSelected += (User obj) => { CaptionTextView.AddUsername(obj.username); }; CharacterCountTextView = view.FindViewById<TextView>(Resource.Id.characterCount); CaptionTextView = view.FindViewById<CharacterLimitedSuggestionEditText>(Resource.Id.caption); CaptionTextView.BindDataToView(CharacterCountTextView, DealWithPostButton, Activity, Suggestions); PostButton = view.FindViewById<ImageButton>(Resource.Id.postbutton); PostButton.Click += async (object sender, EventArgs e) => { string postText = StringUtils.TrimWhiteSpaceAndNewLine(CaptionTextView.Text); if (SelectedImage != null || (!String.IsNullOrEmpty(postText) && CaptionTextView.Text != Strings.add_a_caption_placeholder)) { ProgressDialog progress = new ProgressDialog(Context); progress.Indeterminate = true; progress.SetProgressStyle(ProgressDialogStyle.Spinner); progress.SetMessage(Strings.posting); progress.SetCancelable(false); progress.Show(); try { Byte[] myByteArray = null; if (SelectedImage != null) { MemoryStream stream = new MemoryStream(); SelectedImage = ImageUtils.ReduceSizeIfNeededByWidth(SelectedImage, 1000); SelectedImage.Compress(Bitmap.CompressFormat.Jpeg, 80, stream); myByteArray = stream.ToArray(); } Post result = await TenServices.Post(postText, myByteArray); progress.Dismiss(); if (result != null) { FeedUtils.PassPostToAllFeedsIfExistsWithInclude(result, FeedTypeEnum.FeedType.HomeFeed); TabHostActivity.GetTabHost().tabHost.CurrentTab = 0; ViewUtils.HideKeyboard(TabHostActivity.GetTabHost(), CaptionTextView); ResetPage(); ResetPostImageConstraints(); TabHostActivity.GetTabHost().StartTickNotification(); } } catch (RESTError error) { progress.Dismiss(); Console.WriteLine(error.Message); } } }; DeleteButton = view.FindViewById<ImageButton>(Resource.Id.delete); DeleteButton.BringToFront(); DeleteButton.Click += (sender, e) => { ResetPage(); }; ImageImageView = view.FindViewById<ImageView>(Resource.Id.image); LibraryButton = view.FindViewById<ImageButton>(Resource.Id.library); LibraryButton.Click += (sender, e) => { Intent intent = new Intent(); intent.SetType("image/*"); intent.PutExtra(Intent.ExtraAllowMultiple, true); intent.SetAction(Intent.ActionGetContent); StartActivityForResult(Intent.CreateChooser(intent, "Select Picture"), 1); }; CameraButton = view.FindViewById<ImageButton>(Resource.Id.camera); CameraButton.Click += (sender, e) => { Android.Content.PM.PackageManager pm = Activity.PackageManager; if (pm.HasSystemFeature(Android.Content.PM.PackageManager.FeatureCamera)) { TabHostActivity.GetTabHost().StopTickNotification(); Intent intent = new Intent(Activity, typeof(CameraActivity)); StartActivityForResult(intent, 2); } else { Android.Support.V7.App.AlertDialog.Builder alert = new Android.Support.V7.App.AlertDialog.Builder(Context); alert.SetTitle(Strings.error); alert.SetMessage("No Camera Found"); alert.SetPositiveButton(Strings.ok, (senderAlert, args) => {}); alert.Show(); } }; UsernameTextView = view.FindViewById<TextView>(Resource.Id.username); UserImageWebImage = view.FindViewById<WebImage>(Resource.Id.userimage); return view; }
void ExportBitmapAsPNG(Bitmap bitmap) { Random rnd = new Random(); int RandAssign = rnd.Next(1, 1000000); var filePath = System.IO.Path.Combine("/storage/emulated/0/Pictures", "Drawing"+RandAssign+".png"); var stream = new FileStream (filePath, FileMode.Create); bitmap.Compress(Bitmap.CompressFormat.Png, 100, stream); stream.Close(); Console.WriteLine ("Saved"); }
public ImageData (Bitmap image, string filename) { if (image == null) { throw new ArgumentNullException ("image"); } if (string.IsNullOrEmpty (filename)) { throw new ArgumentException ("filename"); } Image = image; Filename = filename; var compressFormat = Bitmap.CompressFormat.Jpeg; MimeType = "image/jpeg"; if (filename.ToLowerInvariant ().EndsWith (".png")) { MimeType = "image/png"; compressFormat = Bitmap.CompressFormat.Png; } var stream = new MemoryStream (); image.Compress (compressFormat, 100, stream); stream.Position = 0; Data = stream; }
private void CallCloudVision(Android.Graphics.Bitmap bitmap) { _imageDescription.SetText(Resource.String.loading_message); System.Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", @"C:\CatGo-46215182ea6e.json"); try { GoogleCredential credential = GoogleCredential.GetApplicationDefaultAsync().Result; if (credential.IsCreateScopedRequired) { credential = credential.CreateScoped(new[] { VisionService.Scope.CloudPlatform }); } var vision = new VisionService(new BaseClientService.Initializer { HttpClientInitializer = credential, GZipEnabled = false }); var byteArrayOutputStream = new System.IO.MemoryStream(); bitmap.Compress(Bitmap.CompressFormat.Png, 100, byteArrayOutputStream); var byteArray = byteArrayOutputStream.ToArray(); var imageData = Convert.ToBase64String(byteArray); var responses = vision.Images.Annotate( new BatchAnnotateImagesRequest() { Requests = new[] { new AnnotateImageRequest() { Features = new [] { new Feature() { Type = "LABEL_DETECTION" } }, Image = new Image() { Content = imageData } } } }).Execute(); var result = responses.Responses; foreach (var test in result) { foreach (var label in test.LabelAnnotations) { _description += $"{label.Description} ({label.Score}) ."; } } } catch (System.Exception e) { var test = e.InnerException; //needs restart var test2 = System.Environment.GetEnvironmentVariables(EnvironmentVariableTarget.Process); } _imageDescription.Text = _description; }
private static byte[] ToByteArray (Bitmap bitmap) { using (MemoryStream stream = new MemoryStream ()) { bitmap.Compress (Bitmap.CompressFormat.Png, 100, stream); byte[] byteArray = new byte[stream.Length]; stream.Read (byteArray, 0, byteArray.Length); return byteArray; } }
private string SavePhoto(Bitmap bitmap) { string filename = StorageService.GenerateFilename(StorageType.Image, "png"); try { using (System.IO.Stream stream = System.IO.File.OpenWrite(filename)) { bitmap.Compress(Bitmap.CompressFormat.Png, 0, stream); } } catch (Exception) { //TODO : log error return null; } return filename; }
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(); } } }
private void ExtractMediaPickedFromGallery(Intent data) { try { Android.Net.Uri selectedUri = data.Data; String[] columns = { MediaStore.Images.Media.InterfaceConsts.Data, MediaStore.Images.Media.InterfaceConsts.MimeType }; ICursor cursor = ContentResolver.Query(selectedUri, columns, null, null, null); cursor.MoveToFirst(); int pathColumnIndex = cursor.GetColumnIndex(columns[0]); int mimeTypeColumnIndex = cursor.GetColumnIndex(columns[1]); string mimeType = cursor.GetString(mimeTypeColumnIndex); cursor.Close(); PickedMediaFromGallery result = null; if (mimeType.StartsWith("image")) { Android.Graphics.Bitmap bitmap = MediaUtils.GetScaledBitmap( data.Data, MediaUtils.IMAGE_WIDTH_RESTRICTION, MediaUtils.IMAGE_HEIGHT_RESTRICTION, this); if (bitmap == null) { bitmap = MediaStore.Images.Media.GetBitmap(ContentResolver, data.Data); } byte[] bytes; using (MemoryStream memoryStream = new MemoryStream()) { bitmap.Compress(Android.Graphics.Bitmap.CompressFormat.Jpeg, 100, memoryStream); bytes = memoryStream.GetBuffer(); } result = new PickedMediaFromGallery() { DataBase64 = Android.Util.Base64.EncodeToString(bytes, Android.Util.Base64Flags.Default), Completion = true, DataThumbnailBase64 = Android.Util.Base64.EncodeToString(bytes, Android.Util.Base64Flags.Default), MimeType = ProfileMediaService.IMAGE_MEDIA_TYPE }; } else if (mimeType.StartsWith("video")) { string filePath = MediaUtils.GetFileFullPathAlternativeVideo(data.Data, this); Java.IO.File videoFile = new Java.IO.File(filePath); Java.IO.FileInputStream videoFileInputStream = new Java.IO.FileInputStream(videoFile); byte[] videoFileBytes = new byte[videoFile.Length()]; videoFileInputStream.Read(videoFileBytes); videoFileInputStream.Close(); videoFileInputStream.Dispose(); System.IO.Stream thumbnailStream = DependencyService.Get <IPickMediaDependencyService>().GetThumbnail(filePath); byte[] thumbnailBytes; thumbnailStream.Position = 0; using (System.IO.BinaryReader reader = new System.IO.BinaryReader(thumbnailStream)) { thumbnailBytes = reader.ReadBytes((int)thumbnailStream.Length); } result = new PickedMediaFromGallery() { Completion = true, DataBase64 = Android.Util.Base64.EncodeToString(videoFileBytes, Android.Util.Base64Flags.Default), DataThumbnailBase64 = Convert.ToBase64String(thumbnailBytes), FilePath = filePath, MimeType = ProfileMediaService.VIDEO_MEDIA_TYPE }; } else { Debugger.Break(); throw new InvalidOperationException(); } PickMediaTaskCompletion.SetResult(result); } catch (Exception exc) { Debugger.Break(); PickMediaTaskCompletion.SetResult(new PickedMediaFromGallery() { Exception = exc, ErrorMessage = _EXTRACTION_MEDIA_MEDIA_PICK_ERROR }); } }
private void SalvaPedidoPDF() { try { //O PDF sempre será salvo no sdcard string caminho = "mnt/sdcard/Download/invoice.pdf"; System.IO.FileStream fs = new System.IO.FileStream(caminho, System.IO.FileMode.Create); //Create an instance of the document class which represents the PDF document itself. Document document = new Document(PageSize.A4, 25, 25, 30, 30); //Create an instance to the PDF file by creating an instance of the PDF Writer class, using the document and the filestrem in the constructor. PdfWriter writer = PdfWriter.GetInstance(document, fs); //Open the document to enable you to write to the document document.Open(); //Adiciona título Paragraph pgTitulo = new Paragraph(); pgTitulo.Add("Pedido"); pgTitulo.Alignment = Element.ALIGN_CENTER; BaseFont bfTitulo = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, false); pgTitulo.Font = new Font(bfTitulo, Font.BOLD); document.Add(pgTitulo); // Add a simple and well known phrase to the document in a flow layout manner Paragraph pgPedido = new Paragraph("Pedido: " + FindViewById <TextView>(Resource.Id.txtNumOrdem).Text); pgPedido.Add(" "); pgPedido.Add("Data: " + FindViewById <TextView>(Resource.Id.txtData).Text); pgPedido.Add(" "); pgPedido.Add("Hora: " + FindViewById <TextView>(Resource.Id.txtHora).Text); pgPedido.Alignment = Element.ALIGN_LEFT; pgPedido.SpacingBefore = 20; document.Add(pgPedido); Paragraph pgNome = new Paragraph("Cliente: " + FindViewById <TextView>(Resource.Id.txtNome).Text); pgNome.Alignment = Element.ALIGN_LEFT; document.Add(pgNome); Paragraph pgObservacao = new Paragraph("Observação Geral: " + FindViewById <TextView>(Resource.Id.txtObsGeral).Text); pgObservacao.Alignment = Element.ALIGN_LEFT; document.Add(pgObservacao); PdfPTable myTable = new PdfPTable(3); myTable.WidthPercentage = 100; myTable.HorizontalAlignment = 0; myTable.SpacingBefore = 20; myTable.SpacingAfter = 10; float[] sglTblHdWidths = new float[3]; sglTblHdWidths[0] = 300f; sglTblHdWidths[1] = 60f; sglTblHdWidths[2] = 70f; myTable.SetWidths(sglTblHdWidths); PdfPCell CellOneHdr = new PdfPCell(new Phrase("Produto")); CellOneHdr.HorizontalAlignment = Element.ALIGN_CENTER; myTable.AddCell(CellOneHdr); PdfPCell CellTwoHdr = new PdfPCell(new Phrase("Qtde")); CellTwoHdr.HorizontalAlignment = Element.ALIGN_CENTER; myTable.AddCell(CellTwoHdr); PdfPCell CellFourHdr = new PdfPCell(new Phrase("Preço")); CellFourHdr.HorizontalAlignment = Element.ALIGN_CENTER; myTable.AddCell(CellFourHdr); foreach (Produto produto in ListaImprimir) { PdfPCell CellOne = new PdfPCell(new Phrase(produto.DESCR_MAT_CADMAT)); CellOne.HorizontalAlignment = Element.ALIGN_LEFT; myTable.AddCell(CellOne); PdfPCell CellTwo = new PdfPCell(new Phrase(produto.QTD_CADMAT.ToString())); CellTwo.HorizontalAlignment = Element.ALIGN_CENTER; myTable.AddCell(CellTwo); PdfPCell CellFour = new PdfPCell(new Phrase(Convert.ToDouble(produto.PRECO_UNIT).ToString("N2"))); CellFour.HorizontalAlignment = Element.ALIGN_RIGHT; myTable.AddCell(CellFour); } document.Add(myTable); Paragraph pgTotal = new Paragraph("Total do Pedido: " + FindViewById <TextView>(Resource.Id.txtTotal).Text); pgTotal.Alignment = Element.ALIGN_RIGHT; pgTotal.SpacingAfter = 30; document.Add(pgTotal); // Converte a assinatura para byte, e depois para iTextImage SignaturePadView signature = FindViewById <SignaturePadView>(Resource.Id.signatureView); Android.Graphics.Bitmap imagen = signature.GetImage(Android.Graphics.Color.Black, Android.Graphics.Color.White); MemoryStream fstream = new MemoryStream(); imagen.Compress(Bitmap.CompressFormat.Jpeg, 100, fstream); byte[] result = fstream.ToArray(); fstream.Flush(); //Adiciona assinatura ao documento Image imgAssinatura = Image.GetInstance(result); imgAssinatura.ScaleAbsolute(300f, 30f); imgAssinatura.Alignment = Element.ALIGN_CENTER; imgAssinatura.SpacingBefore = 20; document.Add(imgAssinatura); Paragraph pgAssinatura = new Paragraph(); pgAssinatura.Add("Cliente: Sara A. H."); pgAssinatura.Alignment = Element.ALIGN_CENTER; document.Add(pgAssinatura); //Adiciona Copyright Paragraph pgFooter = new Paragraph(); pgFooter.Add("Sara Honorato © 2016 All rights reserved "); pgFooter.Alignment = Element.ALIGN_RIGHT; pgFooter.SpacingBefore = 20; pgFooter.SpacingAfter = 20; document.Add(pgFooter); // Close the document document.Close(); // Close the writer instance writer.Close(); // Always close open file handles explicitly fs.Close(); // Abre o pdf salvo OpenPdf(caminho); } catch (System.Exception ex) { Toast toast = Toast.MakeText(this, "Erro: " + ex.Message, ToastLength.Long); toast.SetGravity(GravityFlags.CenterVertical | GravityFlags.CenterHorizontal, 0, 0); toast.Show(); } }
public void OnSnapshotReady(Bitmap snapshot) { string file = "/mnt/sdcard/test.png";// Java.IO.File file = new Java.IO.File("/mnt/sdcard/test.png"); FileStream outX; //FileOutputStream outX; try { outX = new System.IO.FileStream(file, FileMode.Create); // outX = new FileOutputStream(file); if (snapshot.Compress( Bitmap.CompressFormat.Png, 100, outX)) { outX.Flush(); outX.Close(); } Toast.MakeText(iOnClickListenerImpl.mapControlDemo, "��Ļ��ͼ�ɹ���ͼƬ����: " + file.ToString(), ToastLength.Short).Show(); } catch (FileNotFoundException e) { throw e; } catch (IOException e) { throw e; } }
private string BitmapToBase64String(Bitmap bmp) { using (MemoryStream stream = new MemoryStream()) { if (bmp.Compress(Bitmap.CompressFormat.Png, 100, stream)) { byte[] image = stream.ToArray(); return Convert.ToBase64String(image); } return null; } }
private void apiwork(Android.Graphics.Bitmap bitmap) { string bitmapString = ""; using (var stream = new System.IO.MemoryStream()) { bitmap.Compress(Android.Graphics.Bitmap.CompressFormat.Jpeg, 100, stream); var bytes = stream.ToArray(); bitmapString = System.Convert.ToBase64String(bytes); } //credential is stored in "assets" folder string credPath = "google_api.json"; Google.Apis.Auth.OAuth2.GoogleCredential cred; //Load credentials into object form using (var stream = Assets.Open(credPath)) { cred = Google.Apis.Auth.OAuth2.GoogleCredential.FromStream(stream); } cred = cred.CreateScoped(Google.Apis.Vision.v1.VisionService.Scope.CloudPlatform); // By default, the library client will authenticate // using the service account file (created in the Google Developers // Console) specified by the GOOGLE_APPLICATION_CREDENTIALS // environment variable. We are specifying our own credentials via json file. var client = new Google.Apis.Vision.v1.VisionService(new Google.Apis.Services.BaseClientService.Initializer() { ApplicationName = "subtle-isotope-190917", HttpClientInitializer = cred }); //set up request var request = new Google.Apis.Vision.v1.Data.AnnotateImageRequest(); request.Image = new Google.Apis.Vision.v1.Data.Image(); request.Image.Content = bitmapString; //tell google that we want to perform label detection request.Features = new List <Google.Apis.Vision.v1.Data.Feature>(); request.Features.Add(new Google.Apis.Vision.v1.Data.Feature() { Type = "LABEL_DETECTION" }); var batch = new Google.Apis.Vision.v1.Data.BatchAnnotateImagesRequest(); batch.Requests = new List <Google.Apis.Vision.v1.Data.AnnotateImageRequest>(); batch.Requests.Add(request); //send request. Note that I'm calling execute() here, but you might want to use //ExecuteAsync instead var apiResult = client.Images.Annotate(batch).Execute(); if (bitmap != null) { _imageView.SetImageBitmap(bitmap); _imageView.Visibility = Android.Views.ViewStates.Visible; bitmap = null; } foreach (var item in apiResult.Responses[0].LabelAnnotations) { words.Add(item.Description); } System.GC.Collect(); }
/// <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 }
/// <summary> /// Accepts an image and returns the name that corresponds to the best match /// </summary> /// <param name="theBitmap"></param> /// <returns></returns> private async Task<string> RecognizeImage( Bitmap theBitmap ) { // Initialize the return string string theName = "NotRecognized"; // Clear the current results MatchTextView.Text = ""; MatchImageView.SetImageDrawable( null ); // Encode the camera image byte[] bitmapData; using (var stream = new MemoryStream()) { theBitmap.Compress( Bitmap.CompressFormat.Jpeg, 50, stream ); bitmapData = stream.ToArray(); } string encodedBitmap = Convert.ToBase64String( bitmapData ); // Define the gallery name string GalleryName = "TestCelebs"; // Create JSON request JsonObject jsonParams = new JsonObject(); jsonParams.Add( "image", encodedBitmap ); jsonParams.Add( "gallery_name", GalleryName ); jsonParams.Add( "threshold", MatchThreshold ); // Create an HTTP web request HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create( new Uri( this.ApiUrlRecognize ) ); request.ContentType = "application/json"; request.Method = "POST"; request.Headers.Add( "app_id", AppId ); request.Headers.Add( "app_key", AppKey ); StreamWriter streamWriter = new StreamWriter( request.GetRequestStream() ); streamWriter.Write( jsonParams.ToString() ); streamWriter.Flush(); streamWriter.Close(); // Submit the web request and await the response JsonValue json = await AsyncWebActionJson( request ); try { // Parse the results JsonValue imagesResult = json["images"]; JsonValue attributesResult = imagesResult[0]; // This has to be accessed by the index instead of the name, not sure why JsonValue transactionResult = attributesResult["transaction"]; JsonValue statusResult = transactionResult["status"]; // Check for a successful match if (statusResult.ToString().Contains( "success" )) { JsonValue subjectResult = transactionResult["subject"]; JsonValue confidenceResult = transactionResult["confidence"]; // Get the name as a string //theName = subjectResult + " " + confidenceResult.ToString().Substring( 3, 2 ) + "%"; theName = subjectResult; } else { theName = "No Match"; } } catch( Exception ex ) { } // Return the name return theName; }
/// <exception cref="Couchbase.Lite.CouchbaseLiteException"></exception> public static void AttachImage(Couchbase.Lite.Document task, Bitmap image) { if (task == null || image == null) { return; } UnsavedRevision revision = task.CreateRevision(); 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(); }