public async Task <string> ConvertHtmlToPDF(string html, string fileName) { var dir = new Java.IO.File(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath + "/Download/"); var file = new Java.IO.File(dir + "/" + fileName + ".pdf"); if (!dir.Exists()) { dir.Mkdirs(); } int x = 0; while (file.Exists()) { x++; file = new Java.IO.File(dir + "/" + fileName + "(" + x + ")" + ".pdf"); } var webpage = new Android.Webkit.WebView(MainActivity.Instance); //var windowManager = MainActivity.Instance.GetSystemService(Android.Content.Context.WindowService); //DisplayMetrics outMetrics = new DisplayMetrics(); //windowManager.DefaultDisplay.GetMetrics(outMetrics); //int widthPixels = outMetrics.WidthPixels; //int heightPixels = outMetrics.HeightPixels; //int width = widthPixels; //int height = heightPixels; int width = 2102; int height = 2937; webpage.Layout(0, 0, width, height); var client = new WebViewCallBack(file.ToString()); var tokenSource = new CancellationTokenSource(); var task = Task.Run(() => { if (tokenSource.Token.IsCancellationRequested) { return; } while (true) { if (tokenSource.Token.IsCancellationRequested) { break; } } }, tokenSource.Token); client.OnPageLoadFinished += (s, e) => { tokenSource.Cancel(); }; webpage.SetWebViewClient(client); webpage.LoadDataWithBaseURL("", html, "text/html", "UTF-8", null); await task; return(file.ToString()); }
//// SurfaceTexture callback //[MethodImpl(MethodImplOptions.Synchronized)] //public void OnFrameAvailable(SurfaceTexture st) //{ // //if (VERBOSE) Log.d(TAG, "new frame available"); // Monitor.Enter(mFrameSyncObject); // try // { // if (mFrameAvailable) // { // throw new System.Exception("mFrameAvailable already set, frame could be dropped"); // } // mFrameAvailable = true; // Monitor.PulseAll(mFrameSyncObject); // } // finally // { // Monitor.Exit(mFrameSyncObject); // } //} /** * Saves the current frame to disk as a PNG image. */ public void saveFrame(String filename) { // glReadPixels gives us a ByteBuffer filled with what is essentially big-endian RGBA // data (i.e. a byte of red, followed by a byte of green...). To use the Bitmap // constructor that takes an int[] array with pixel data, we need an int[] filled // with little-endian ARGB data. // // If we implement this as a series of buf.get() calls, we can spend 2.5 seconds just // copying data around for a 720p frame. It's better to do a bulk get() and then // rearrange the data in memory. (For comparison, the PNG compress takes about 500ms // for a trivial frame.) // // So... we set the ByteBuffer to little-endian, which should turn the bulk IntBuffer // get() into a straight memcpy on most Android devices. Our ints will hold ABGR data. // Swapping B and R gives us ARGB. We need about 30ms for the bulk get(), and another // 270ms for the color swap. // // We can avoid the costly B/R swap here if we do it in the fragment shader (see // http://stackoverflow.com/questions/21634450/ ). // // Having said all that... it turns out that the Bitmap#copyPixelsFromBuffer() // method wants RGBA pixels, not ARGB, so if we create an empty bitmap and then // copy pixel data in we can avoid the swap issue entirely, and just copy straight // into the Bitmap from the ByteBuffer. // // Making this even more interesting is the upside-down nature of GL, which means // our output will look upside-down relative to what appears on screen if the // typical GL conventions are used. (For ExtractMpegFrameTest, we avoid the issue // by inverting the frame when we render it.) // // Allocating large buffers is expensive, so we really want mPixelBuf to be // allocated ahead of time if possible. We still get some allocations from the // Bitmap / PNG creation. mPixelBuf.Rewind(); GLES20.GlReadPixels(0, 0, mWidth, mHeight, GLES20.GlRgba, GLES20.GlUnsignedByte, mPixelBuf); var createfilepath = new Java.IO.File(_filesdir, filename + ".bmp").AbsolutePath; using (FileStream bos = new FileStream(createfilepath, FileMode.CreateNew)) { try { Bitmap bmp = Bitmap.CreateBitmap(mWidth, mHeight, Bitmap.Config.Argb8888); mPixelBuf.Rewind(); bmp.CopyPixelsFromBuffer(mPixelBuf); bmp.Compress(Bitmap.CompressFormat.Png, 90, bos); bmp.Recycle(); } finally { bos.Close(); } } //if (VERBOSE) { // Log.d(TAG, "Saved " + mWidth + "x" + mHeight + " frame as '" + filename + "'"); //} }
private void InitializeCamera(object sender, EventArgs eventArgs) { Intent intent = new Intent(MediaStore.ActionImageCapture); var documentsDirectry = ApplicationContext.GetExternalFilesDir(Android.OS.Environment.DirectoryPictures); cameraFile = new Java.IO.File(documentsDirectry, "default_image" + "." + FileFormatEnum.JPEG.ToString()); Android.Net.Uri photoURI = FileProvider.GetUriForFile(ApplicationContext, ApplicationContext.PackageName + ".provider", cameraFile); intent.PutExtra(MediaStore.ExtraOutput, photoURI); StartActivityForResult(intent, 0); }
//Method to save document as a file in Android and view the saved document public async Task SaveAndView(string fileName, String contentType, MemoryStream stream) { string root = null; if (ContextCompat.CheckSelfPermission(Forms.Context, Manifest.Permission.WriteExternalStorage) != Permission.Granted) { ActivityCompat.RequestPermissions((Android.App.Activity)Forms.Context, new String[] { Manifest.Permission.WriteExternalStorage }, 1); } //Get the root path in android device. if (Android.OS.Environment.IsExternalStorageEmulated) { root = Android.OS.Environment.ExternalStorageDirectory.ToString(); } else { root = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); } //Create directory and file Java.IO.File myDir = new Java.IO.File(root + "/Syncfusion"); myDir.Mkdir(); Java.IO.File file = new Java.IO.File(myDir, fileName); //Remove if the file exists if (file.Exists()) { file.Delete(); } //Write the stream into the file FileOutputStream outs = new FileOutputStream(file); outs.Write(stream.ToArray()); outs.Flush(); outs.Close(); //Invoke the created file for viewing if (file.Exists()) { string extension = Android.Webkit.MimeTypeMap.GetFileExtensionFromUrl(Android.Net.Uri.FromFile(file).ToString()); string mimeType = Android.Webkit.MimeTypeMap.Singleton.GetMimeTypeFromExtension(extension); Intent intent = new Intent(Intent.ActionView); intent.SetFlags(ActivityFlags.ClearTop | ActivityFlags.NewTask); Android.Net.Uri path = FileProvider.GetUriForFile(Forms.Context, Android.App.Application.Context.PackageName + ".fileprovider", file); intent.SetDataAndType(path, mimeType); intent.AddFlags(ActivityFlags.GrantReadUriPermission); Forms.Context.StartActivity(Intent.CreateChooser(intent, "Choose App")); } }
private static void DeletePhotoFromDisk(Java.IO.File file) { try { var deleted = file.Delete(); if (!deleted) { _logger.LogInfo($"File has not been deleted: {file.AbsolutePath}"); } } catch (Exception e) { _logger.LogError($"Can't delete file: {file.AbsolutePath}", e); } finally { file.Dispose(); } }
public async void PutKeysButtonOnClick() { File directory; // Shared key list file, Please configure according to the actual situation if (Android.OS.Environment.ExternalStorageState == "mounted") { //create new file directory object directory = FilesDir; if (directory.Exists()) { Toast.MakeText(this, "File exist.", ToastLength.Short).Show(); } string fileName = directory.ToString() + "/putkeysfile.zip"; File file = new Java.IO.File(fileName); if (!file.Exists()) { file.CreateNewFile(); } else { List <File> putList = new List <File>(); putList.Add(file); DiagnosisConfiguration diagnosisConfiguration = new DiagnosisConfiguration.Builder().Build(); PendingIntent pendingIntent = PendingIntent.GetService(this, 0, new Intent(this, typeof(BackgroundContactCheckingIntentService)), PendingIntentFlags.UpdateCurrent); //Put shared key files to diagnosisconfiguration. var resultPutSharedKeys = mEngine.PutSharedKeyFilesAsync(pendingIntent, putList, diagnosisConfiguration, token); await resultPutSharedKeys; if (resultPutSharedKeys.Status.Equals(System.Threading.Tasks.TaskStatus.RanToCompletion)) { Log.Debug(TAG, "PutSharedKeyFiles succeeded."); } } } }
private static async Task <Java.IO.File> SavePhotoToDiskAsync(byte[] data, string directory) { Java.IO.File pictureFile; string photoFileName; using (var pictureFileDir = new Java.IO.File(directory)) { if (!pictureFileDir.Exists() && !pictureFileDir.Mkdirs()) { _logger.LogError("Can't create directory to save image"); return(null); } photoFileName = $"Picture-{Guid.NewGuid().ToString()}.jpg"; var imageFilePath = $"{pictureFileDir.Path}{Java.IO.File.Separator}{photoFileName}"; pictureFile = new Java.IO.File(imageFilePath); } FileOutputStream fileOutputStream = null; try { fileOutputStream = new FileOutputStream(pictureFile); await fileOutputStream.WriteAsync(data); } catch (Exception e) { _logger.LogError($"File {photoFileName} has not been saved: {e.Message}", e); } finally { fileOutputStream?.Close(); fileOutputStream?.Dispose(); } return(pictureFile); }
private bool saveRgbImage(string prefix, float score, int[] rgb, int width, int height) { bool success = false; if (rgb == null) { return(success); } if (!Environment.IsExternalStorageEmulated) { return(success); } Java.IO.File sdCard = Environment.ExternalStorageDirectory; string uuid = Guid.NewGuid().ToString(); File dir = new File(sdCard.AbsolutePath + "/rgb_ir_depth/" + uuid); if (!dir.Exists()) { dir.Mkdirs(); } string rgbFilename = string.Format("%s_%s_%s.jpg", prefix, "rgb", score); File rgbFile = new File(dir, rgbFilename); if (rgbFile.Exists()) { rgbFile.Delete(); } System.IO.FileStream fos = null; try { fos = new System.IO.FileStream(rgbFile.Path, System.IO.FileMode.Open); Bitmap bitmap = Bitmap.CreateBitmap(rgb, width, height, Bitmap.Config.Argb8888); Log.Info(TAG, "strFileName 1= " + rgbFile.Path); if (null != fos) { bitmap.Compress(Bitmap.CompressFormat.Jpeg, 100, fos); fos.Flush(); fos.Close(); success = true; } } catch (Java.IO.FileNotFoundException e) { e.PrintStackTrace(); } catch (Java.IO.IOException e) { e.PrintStackTrace(); } finally { if (fos != null) { try { fos.Close(); } catch (Java.IO.IOException e) { e.PrintStackTrace(); } } } return(success); }
public void PrepareEncoder(string path, File _downloaddir) { MediaCodec _Decoder = null; MediaExtractor extractor = null; _downloadsfilesdir = _downloaddir; try { //for (int i = 0; i < extractor.TrackCount; i++) //{ // MediaFormat Format = extractor.GetTrackFormat(i); // //MediaFormat format = MediaFormat.CreateVideoFormat(MIME_TYPE, 640, 360); // String mime = Format.GetString(MediaFormat.KeyMime); // if (mime.StartsWith("video/")) // { // extractor.SelectTrack(i); // _Decoder = MediaCodec.CreateEncoderByType(mime); // _Decoder.Configure(Format, null, null, 0); // break; // } //} extractor = new MediaExtractor(); extractor.SetDataSource(path); int trackIndex = selectTrack(extractor); //if (trackIndex < 0) //{ // throw new RuntimeException("No video track found in " + inputFile); //} extractor.SelectTrack(trackIndex); MediaFormat format = extractor.GetTrackFormat(trackIndex); _Width = format.GetInteger(MediaFormat.KeyWidth); _Height = format.GetInteger(MediaFormat.KeyHeight); // Could use width/height from the MediaFormat to get full-size frames. //outputSurface = new CodecOutputSurface(saveWidth, saveHeight); // Create a MediaCodec decoder, and configure it with the MediaFormat from the // extractor. It's very important to use the format from the extractor because // it contains a copy of the CSD-0/CSD-1 codec-specific data chunks. String mime = format.GetString(MediaFormat.KeyMime); _Decoder = MediaCodec.CreateDecoderByType(mime); _Decoder.Configure(format, null, null, 0); _Decoder.Start(); Decode(_Decoder, extractor); } catch (Exception e) { Log.Error(TAG, e.Message, e); throw; } finally { // release everything we grabbed //if (outputSurface != null) //{ // outputSurface.release(); // outputSurface = null; //} if (_Decoder != null) { _Decoder.Stop(); _Decoder.Release(); _Decoder = null; } if (extractor != null) { extractor.Release(); extractor = null; } } _TrackIndex = -1; //_MuxerStarted = false; }