public async Task <string> ImageSave(MemoryStream stream, bool compatibleMode, string fileName = null) { await Permissions.RequestAsync <Permissions.StorageWrite>(); if (Permissions.ShouldShowRationale <Permissions.StorageWrite>()) { return("...保存个屁!不给爷权限还想让爷造坦克?"); } await Permissions.RequestAsync <Permissions.StorageRead>(); if (Permissions.ShouldShowRationale <Permissions.StorageRead>()) { return("...保存个屁!不给爷权限还想让爷造坦克?"); } //用于替代Environment.ExternalStorageDirectory //GetExternalFilesDir()会获取到 /storage/emulated/0/Android/data/应用包名/files string externalRootPath; if (compatibleMode) { externalRootPath = "/storage/emulated/0/"; } else { DirectoryInfo externalStorageDir = new DirectoryInfo(Platform.AppContext.GetExternalFilesDir(null).AbsolutePath); externalRootPath = externalStorageDir.Parent.Parent.Parent.Parent.FullName; } string path = Path.Combine(externalRootPath, Environment.DirectoryPictures, albumName); if (fileName == null || fileName == "") { fileName = "Tank_" + DateTime.Now.ToLocalTime().ToString("yyyyMMdd_HHmmss") + ".png"; } try { if (Directory.Exists(path) == false) { Directory.CreateDirectory(path); } } catch (UnauthorizedAccessException) { return("。。。保存失败!创建目录失败!!动态获取的目录为:" + path + "请尝试兼容模式!!"); } path = Path.Combine(path, fileName); FileStream photoTankFile = new FileStream(path, FileMode.Create); byte[] photoTank = stream.ToArray(); photoTankFile.Write(photoTank, 0, photoTank.Length); photoTankFile.Flush(); photoTankFile.Close(); string[] paths = { path }; MediaScannerConnection.ScanFile(Platform.AppContext, paths, null, null); return(Path.Combine(fileName)); }
// Saving photos requires android.permission.WRITE_EXTERNAL_STORAGE in AndroidManifest.xml public async Task <bool> SavePhotoAsync(byte[] data, string folder, string filename) { try { File picturesDirectory = Environment.GetExternalStoragePublicDirectory(Environment.DirectoryPictures); File folderDirectory = picturesDirectory; if (!string.IsNullOrEmpty(folder)) { folderDirectory = new File(picturesDirectory, folder); folderDirectory.Mkdirs(); } using (File bitmapFile = new File(folderDirectory, filename)) { bitmapFile.CreateNewFile(); using (FileOutputStream outputStream = new FileOutputStream(bitmapFile)) { await outputStream.WriteAsync(data); } // Make sure it shows up in the Photos gallery promptly. MediaScannerConnection.ScanFile(MainActivity.Instance, new string[] { bitmapFile.Path }, new string[] { "image/png", "image/jpeg" }, null); } } catch { return(false); } return(true); }
private void WireButtons() { Button imageButton = FindViewById <Button>(Resource.Id.MyButton); Button scanButton = FindViewById <Button>(Resource.Id.scanButton); Button newlineButton = FindViewById <Button>(Resource.Id.newlineButton); imageButton.Click += delegate { try { var f = CreateImage(); MediaScannerConnection.ScanFile(this, new String[] { f.AbsolutePath }, null, null); Log.Info(A.B, "Created image: " + f.Path); } catch (Exception e) { Log.Error(A.B, "Error creting image: " + e.Message); } }; scanButton.Click += delegate { try { ScanForMedia(); } catch (Exception e) { Log.Error(A.B, "Error scanning for images: " + e.Message); } }; newlineButton.Click += delegate { Log.Debug(A.B, "_"); }; }
public async Task <bool> SaveJsonAsync(string data, string folder, string filename) { try { File picturesDirectory = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryPictures); File folderDirectory = picturesDirectory; if (!string.IsNullOrEmpty(folder)) { folderDirectory = new File(picturesDirectory, folder); folderDirectory.Mkdirs(); } using (File textFile = new File(folderDirectory, filename)) { textFile.CreateNewFile(); using (FileOutputStream outputStream = new FileOutputStream(textFile)) { await outputStream.WriteAsync(System.Text.Encoding.ASCII.GetBytes(data)); } // Make sure it shows up in the Photos gallery promptly. MediaScannerConnection.ScanFile(MainActivity.Instance, new string[] { textFile.Path }, new string[] { "application/json" }, null); } } catch (Exception ex) { throw new Exception(ex.Message); } return(true); }
/** * Writes a message to the log file on the device. * @param logMessageTag A tag identifying a group of log messages. * @param logMessage The message to add to the log. */ private static void logToFile(Context context, string logMessageTag, string logMessage) { try { // Gets the log file from the root of the primary storage. If it does // not exist, the file is created. File logFile = new File(System.Environment.CurrentDirectory, "TestApplicationLog.txt"); if (!logFile.Exists()) { logFile.CreateNewFile(); } // Write the message to the log with a timestamp BufferedWriter writer = new BufferedWriter(new FileWriter(logFile, true)); writer.Write(string.Format("%1s [%2s]:%3s\r\n", getDateTimeStamp(), logMessageTag, logMessage)); writer.Close(); // Refresh the data so it can seen when the device is plugged in a // computer. You may have to unplug and replug to see the latest // changes MediaScannerConnection.ScanFile(context, new string[] { logFile.ToString() }, null, null); } catch (IOException) { Log.Error("com.cindypotvin.Logger", "Unable to log exception to file."); } }
private void SaveImageLocally() { // figure out the filepath and filename to save to String saveFileName = "FEHTeam" + DateTime.Now.ToFileTime() + ".png"; // check if user has a filename specified if (outFileName.Trim().Length > 0) { saveFileName = outFileName + ".png"; } // save the result image var sdCardPath = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryPictures).AbsolutePath; var filePath = System.IO.Path.Combine(sdCardPath, saveFileName); var stream = new FileStream(filePath, FileMode.Create); bitmap.Compress(Bitmap.CompressFormat.Png, 100, stream); stream.Close(); bitmap.Recycle(); // call the Media Scanner to let the gallery (and everything that uses it) // know that there is a new picture we saved and makes it visible to them MediaScannerConnection.ScanFile(MainActivity.GetAppContext(), new String[] { sdCardPath + "/" + saveFileName }, null, null); // notify the user that the file is saved Toast.MakeText(MainActivity.GetAppContext(), "File has been saved!", ToastLength.Short).Show(); }
public void OnImageSaved(ImageCapture.OutputFileResults output) { var savedUri = output.SavedUri != null ? output.SavedUri : Uri.FromFile(photoFile); Log.Debug(Tag, "Photo capture succeeded: " + savedUri); // We can only change the foreground Drawable using API level 23+ API if (Build.VERSION.SdkInt >= BuildVersionCodes.M) { // Update the gallery thumbnail with latest picture taken SetGalleryThumbnail(savedUri); } // Implicit broadcasts will be ignored for devices running API level >= 24 // so if you only target API level 24+ you can remove this statement if (Build.VERSION.SdkInt < BuildVersionCodes.N) { RequireActivity().SendBroadcast(new Intent(Android.Hardware.Camera.ActionNewPicture, savedUri)); } // If the folder selected is an external media directory, this is // unnecessary but otherwise other apps will not be able to access our // images unless we scan them using [MediaScannerConnection] var mimeType = MimeTypeMap.Singleton .GetMimeTypeFromExtension(System.IO.Path.GetExtension(savedUri.Path)); MediaScannerConnection.ScanFile( Context, new string[] { savedUri.Path }, new string[] { mimeType }, this); }
public async Task <bool> SavePhotoAsync(byte[] data, string folder, string filename) { try { var status = await CrossPermissions.Current.CheckPermissionStatusAsync(Permission.Storage); if (status != PermissionStatus.Granted) { var results = await CrossPermissions.Current.RequestPermissionsAsync(Permission.Storage); //Best practice to always check that the key exists if (results.ContainsKey(Permission.Storage)) { status = results[Permission.Storage]; } } if (status == PermissionStatus.Granted) { try { File picturesDirectory = Environment.GetExternalStoragePublicDirectory(Environment.DirectoryPictures); File folderDirectory = picturesDirectory; if (!string.IsNullOrEmpty(folder)) { folderDirectory = new File(picturesDirectory, folder); folderDirectory.Mkdirs(); } using (File bitmapFile = new File(folderDirectory, filename)) { bitmapFile.CreateNewFile(); using (FileOutputStream outputStream = new FileOutputStream(bitmapFile)) { await outputStream.WriteAsync(data); } // Make sure it shows up in the Photos gallery promptly. MediaScannerConnection.ScanFile(MainActivity.Instance, new string[] { bitmapFile.Path }, new string[] { "image/png", "image/jpeg" }, null); } } catch (Exception ex) { System.Console.WriteLine("Save Error: " + ex); return(false); } } } catch (Exception ex) { System.Console.WriteLine("Permission Error: " + ex); return(false); } return(true); }
public async Task <bool> SaveBitmap(byte[] buffer, string filename) { try { File picturesDirectory = Environment.GetExternalStoragePublicDirectory(Environment.DirectoryPictures); File PaintDirectory = new File(picturesDirectory, "Pepper"); PaintDirectory.Mkdirs(); using (File bitmapFile = new File(PaintDirectory, filename)) { bitmapFile.CreateNewFile(); using (FileOutputStream outputStream = new FileOutputStream(bitmapFile)) { await outputStream.WriteAsync(buffer); } // Make sure it shows up in the Photos gallery promptly. MediaScannerConnection.ScanFile(Forms.Context, new string[] { bitmapFile.Path }, new string[] { "image/png", "image/jpeg" }, null); } } catch { return(true); } return(true); }
/// <summary> /// saves and shares the final video. /// </summary> /// <param name="c">C.</param> /// <param name="fileName">File name.</param> private void CreateVideoShareIntent(Context c, string fileName) { File publicDir = new File( global::Android.OS.Environment.GetExternalStoragePublicDirectory(global::Android.OS.Environment.DirectoryMovies).Path, File.Separator + "Gifaroo"); publicDir.Mkdir(); File externalFile = new File(publicDir.Path + File.Separator, finalFileName); try{ CopyFileFromInternalToExternalDirectory(c, fileName, externalFile); }catch (Exception ex) { Log.Debug("GIFAROO", "Failed to copy from internal to external! -- \n" + ex); //TODO: Remove Toast.MakeText(c, "Error saving file! Make sure that you have enough space.", ToastLength.Long).Show(); } xMediaScannerConnection meddiaScannerConnection = new xMediaScannerConnection(); meddiaScannerConnection.EOnScanCompleted += (object sender, EventArgs e) => { global::Android.Net.Uri vidUri = global::Android.Net.Uri.FromFile(externalFile); Intent shareIntent = new Intent(); shareIntent.SetAction(Intent.ActionSend); shareIntent.PutExtra(Intent.ExtraStream, vidUri); shareIntent.SetType("video/*"); StartActivity(Intent.CreateChooser(shareIntent, "Open with...")); }; MediaScannerConnection.ScanFile(c, new string[] { externalFile.ToString() }, null, meddiaScannerConnection); }
/// <summary> /// Saves photo to photo library /// </summary> /// <param name="data">image data to save</param> /// <param name="folder">folder name in photo libray to use</param> /// <param name="filename">filename of image to save</param> /// <returns>task to wait on</returns> public async Task SavePhotoAsync(byte[] data, string folder, string filename) { #pragma warning disable CS0618 // Type or member is obsolete File picturesDirectory = Environment.GetExternalStoragePublicDirectory( Environment.DirectoryPictures); #pragma warning restore CS0618 // Type or member is obsolete File folderDirectory = picturesDirectory; if (!string.IsNullOrEmpty(folder)) { folderDirectory = new File(picturesDirectory, folder); folderDirectory.Mkdirs(); } using File bitmapFile = new File(folderDirectory, filename); bitmapFile.CreateNewFile(); using (FileOutputStream outputStream = new FileOutputStream(bitmapFile)) { await outputStream.WriteAsync(data); } // Make sure it shows up in the Photos gallery promptly. MediaScannerConnection.ScanFile( Xamarin.Essentials.Platform.CurrentActivity, new string[] { bitmapFile.Path }, new string[] { "image/png", "image/jpeg" }, null); }
private void DeleteFromGallery(string fileName) { ContentResolver contentResolver = MainActivity.ActivityContext.ApplicationContext.ContentResolver; int index = fileName.LastIndexOf("."); fileName = fileName.Substring(0, index - 1); long ticks = Convert.ToInt64(fileName); DateTime dt = new DateTime(ticks); Java.IO.File file = new Java.IO.File(Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDcim), "/Camera"); var images = file.ListFiles(); foreach (Java.IO.File f in file.ListFiles()) { f.Delete(); MediaScannerConnection.ScanFile(MainActivity.ActivityContext.ApplicationContext, new String[] { f.Path }, null, null); //contentResolver.Delete(Uri.FromFile(f), null, null); } //var file2 = new Java.IO.File(file.AbsolutePath, fileName); //bool deleted = file2.Delete(); }
public async Task <bool> SaveBitmap(byte[] bitmapData, string filename) { try { File picturesDirectory = Environment.GetExternalStoragePublicDirectory(Environment.DirectoryPictures); File spinPaintDirectory = new File(picturesDirectory, "PhotoCollage"); spinPaintDirectory.Mkdirs(); using (File bitmapFile = new File(spinPaintDirectory, filename)) { bitmapFile.CreateNewFile(); using (FileOutputStream outputStream = new FileOutputStream(bitmapFile)) { await outputStream.WriteAsync(bitmapData); } MediaScannerConnection.ScanFile(Android.App.Application.Context, new string[] { bitmapFile.Path }, new string[] { "image/png", "image/jpeg" }, null); return(true); } } catch (Exception ex) { Toast.MakeText(Android.App.Application.Context, ex.Message, ToastLength.Long).Show(); return(false); } }
public async Task <bool> SaveXml(string content, string filename) { try { File picturesDirectory = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDocuments); File folderDirectory = picturesDirectory; using (File xmlFile = new File(folderDirectory, filename)) { xmlFile.CreateNewFile(); using (FileOutputStream outputStream = new FileOutputStream(xmlFile)) { await outputStream.WriteAsync(UTF8Encoding.UTF8.GetBytes(content)); } // Make sure it shows up in the Photos gallery promptly. MediaScannerConnection.ScanFile(MainActivity.Instance, new string[] { xmlFile.Path }, new string[] { "application/xml" }, null); } } catch (Exception ex) { throw new Exception(ex.Message); } return(true); }
public async Task <bool> SaveBitmap(byte[] buffer, string filename) { try { File picturesDirectory = Environment.GetExternalStoragePublicDirectory(Environment.DirectoryPictures); File spinPaintDirectory = new File(picturesDirectory, "SpinPaint"); spinPaintDirectory.Mkdirs(); using (File bitmapFile = new File(spinPaintDirectory, filename)) { bitmapFile.CreateNewFile(); using (FileOutputStream outputStream = new FileOutputStream(bitmapFile)) { await outputStream.WriteAsync(buffer); } // Make sure it shows up in the Photos gallery promptly. MediaScannerConnection.ScanFile(MainActivity.Instance, new string[] { bitmapFile.Path }, new string[] { "image/png", "image/jpeg" }, null); } } catch (System.Exception ex) { return(false); } return(true); }
private void BtnSave_Click(object sender, EventArgs e) { try { if (ValidateControls()) { string folderPath = Path.Combine(clsGlobal.FilePath, clsGlobal.FileFolder); if (!Directory.Exists(folderPath)) { Directory.CreateDirectory(folderPath); } string filename = Path.Combine(folderPath, clsGlobal.ServerIpFileName); using (var streamWriter = new StreamWriter(filename, false)) { streamWriter.WriteLine(editServerIP.Text.Trim()); streamWriter.WriteLine(editPort.Text.Trim()); streamWriter.WriteLine("LINE=" + cmbSite.SelectedItem.ToString()); MediaScannerConnection.ScanFile(this, new string[] { filename }, null, null); Toast.MakeText(this, "Setting saved", ToastLength.Long).Show(); clsGlobal.mSockIp = editServerIP.Text.Trim(); clsGlobal.mSockPort = Convert.ToInt32(editPort.Text.Trim()); Finish(); } } } catch (Exception ex) { clsGLB.ShowMessage(ex.Message, this, MessageTitle.ERROR); } }
private async Task TakeScreenshot() { RunOnUiThread(() => { _commentView.Visibility = ViewStates.Visible; _gridView.Visibility = ViewStates.Invisible; _drawView.Visibility = ViewStates.Invisible; _pilotVienna.Visibility = ViewStates.Invisible; _pilotTim.Visibility = ViewStates.Invisible; _pilotMario.Visibility = ViewStates.Invisible; _pilotTwan.Visibility = ViewStates.Invisible; _pilotJudith.Visibility = ViewStates.Invisible; _pilotSanne.Visibility = ViewStates.Invisible; }); await Task.Delay(50).ConfigureAwait(false); _root.DrawingCacheEnabled = true; _root.BuildDrawingCache(true); var bitmap = Bitmap.CreateBitmap(_root.DrawingCache); _root.DrawingCacheEnabled = false; var fileName = string.Format("{0}.png", DateTimeOffset.Now.ToString()); var basePath = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath; var filePath = System.IO.Path.Combine(basePath, "United Wings", fileName); if (!Directory.Exists(System.IO.Path.Combine(basePath, "United Wings"))) { Directory.CreateDirectory(System.IO.Path.Combine(basePath, "United Wings")); } var stream = new FileStream(filePath, FileMode.Create); await bitmap.CompressAsync(Bitmap.CompressFormat.Png, 100, stream).ConfigureAwait(false); stream.Close(); RunOnUiThread(() => { _commentView.Visibility = ViewStates.Invisible; _gridView.Visibility = ViewStates.Visible; _drawView.Visibility = ViewStates.Visible; _pilotVienna.Visibility = ViewStates.Visible; _pilotTim.Visibility = ViewStates.Visible; _pilotMario.Visibility = ViewStates.Visible; _pilotTwan.Visibility = ViewStates.Visible; _pilotJudith.Visibility = ViewStates.Visible; _pilotSanne.Visibility = ViewStates.Visible; Toast.MakeText(BaseContext, "Screenshot saved", ToastLength.Short).Show(); }); MediaScannerConnection.ScanFile(ApplicationContext, new string[] { filePath }, null, this); }
// シャッターを切った時のコールバック public void OnPictureTaken(byte[] data, AndroidCamera camera) { try { var SaveDir = new Java.IO.File(Environment.GetExternalStoragePublicDirectory(Environment.DirectoryDcim), "Camera"); if (!SaveDir.Exists()) { SaveDir.Mkdir(); } // 非同期で画像の回転・保存・アルバムへの登録 Task.Run(async() => { // 保存ディレクトリに入ってるファイル数をカウント var Files = SaveDir.List(); int count = 0; foreach (var tmp in Files) { count++; } Matrix matrix = new Matrix(); // 回転用の行列 matrix.SetRotate(90 - DetectScreenOrientation()); Bitmap original = BitmapFactory.DecodeByteArray(data, 0, data.Length); Bitmap rotated = Bitmap.CreateBitmap(original, 0, 0, original.Width, original.Height, matrix, true); var FileName = new Java.IO.File(SaveDir, "DCIM_" + (count + 1) + ".jpg"); // ファイルをストレージに保存 FileStream stream = new FileStream(FileName.ToString(), FileMode.CreateNew); await rotated.CompressAsync(Bitmap.CompressFormat.Jpeg, 90, stream); stream.Close(); Android.Media.ExifInterface Exif = new ExifInterface(FileName.ToString()); Exif.SetAttribute(ExifInterface.TagGpsLatitude, Latitude); Exif.SetAttribute(ExifInterface.TagGpsLongitude, Longitude); Exif.SetAttribute(ExifInterface.TagGpsLatitudeRef, "N"); Exif.SetAttribute(ExifInterface.TagGpsLongitudeRef, "E"); Exif.SaveAttributes(); // 保存したファイルをアルバムに登録 string[] FilePath = { Environment.GetExternalStoragePublicDirectory(Environment.DirectoryDcim) + "/Camera/" + "DCIM_" + (count + 1) + ".jpg" }; string[] mimeType = { "image/jpeg" }; MediaScannerConnection.ScanFile(ApplicationContext, FilePath, mimeType, null); RunOnUiThread(() => { Toast.MakeText(ApplicationContext, "保存しました\n" + FileName, ToastLength.Short).Show(); }); original.Recycle(); rotated.Recycle(); isTakeEnabled = false; }); m_Camera.StartPreview(); } catch (Exception e) { Console.WriteLine(e.Message); } }
public override void onCreate(Bundle savedInstanceState) { base.onCreate(savedInstanceState); ContentView = R.layout.video_player_layout; setupViewElements(); mSmcLib = new Smc(); try { mSmcLib.initialize(BaseContext); } catch (SsdkUnsupportedException e) { Console.WriteLine(e.ToString()); Console.Write(e.StackTrace); //TODO Handle exceptions. } Log.d("media control lib version", mSmcLib.VersionName); // Prepares assets used by sample. extractAssets(); // Restores saved state, after e.g. rotating. if (savedInstanceState != null) { mState = new VideoPlayerState(savedInstanceState); } else { mState = new VideoPlayerState(); // Initializes state with built-in content. File storageDir = new File(Environment.ExternalStorageDirectory, ASSETS_SUBDIR); File video = new File(storageDir, VIDEO_FILE); File subtitles = new File(storageDir, SUBTITLES_FILE); // Gets media information (title, artist, cover) MediaScannerConnection.scanFile(ApplicationContext, new string[] { video.AbsolutePath }, null, this); Uri mediaUri = Uri.fromFile(video); Uri subtitlesUri = Uri.fromFile(subtitles); mState.mMediaUri = mediaUri; mState.mSubtitlesUri = subtitlesUri; mState.mTitle = "Sample album"; string path = mediaUri.Path; if (path != null && path.LastIndexOf(".", StringComparison.Ordinal) != -1) { string ext = path.Substring(path.LastIndexOf(".", StringComparison.Ordinal) + 1); mState.mMimeType = MimeTypeMap.Singleton.getMimeTypeFromExtension(ext); } } }
static Task DoSaveToAlbum(FileInfo file) { var isPhoto = file.GetMimeType().StartsWith("image"); var mediaType = isPhoto ? Android.OS.Environment.DirectoryPictures : Android.OS.Environment.DirectoryMovies; var directory = new DirectoryInfo(Android.OS.Environment.GetExternalStoragePublicDirectory(mediaType).Path) .GetOrCreateSubDirectory(Device.IO.Root.Name); if (!directory.Exists()) { throw new IOException("Failed to create directory " + directory.Name); } var destination = directory.GetFile(file.Name); if (destination.Exists()) { var num = 1; while (true) { destination = directory.GetFile(file.NameWithoutExtension() + " " + num + file.Extension); if (!destination.Exists()) { break; } num++; } } file.CopyTo(destination); try { MediaScannerConnection.ScanFile(UIRuntime.CurrentActivity, new[] { destination.FullName }, null, null); var values = new ContentValues(); values.Put(MediaStore.Images.Media.InterfaceConsts.Title, destination.NameWithoutExtension()); values.Put(MediaStore.Images.Media.InterfaceConsts.Description, string.Empty); values.Put(MediaStore.Images.Media.InterfaceConsts.DateTaken, Java.Lang.JavaSystem.CurrentTimeMillis()); values.Put(MediaStore.Images.ImageColumns.BucketId, destination.FullName.GetHashCode()); values.Put(MediaStore.Images.ImageColumns.BucketDisplayName, destination.Name.ToLowerInvariant()); values.Put("_data", destination.FullName); UIRuntime.CurrentActivity.ContentResolver.Insert(MediaStore.Images.Media.ExternalContentUri, values); } catch (Exception ex) { Log.For(typeof(Media)).Error(ex, "Failed to save to scan file."); } var publicUri = Android.Net.Uri.FromFile(new Java.IO.File(destination.FullName)); var mediaScanIntent = new Intent(Intent.ActionMediaScannerScanFile, publicUri); UIRuntime.CurrentActivity.SendBroadcast(mediaScanIntent); return(Task.CompletedTask); }
public override void OnDestroy() { sensorManager.UnregisterListener(this); streamWriter.Close(); streamWriter.Dispose(); fileStream.Close(); fileStream.Dispose(); MediaScannerConnection.ScanFile(this, new string[] { Storage.RawFolderName }, null, null); StopForeground(true); base.OnDestroy(); }
//JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: //ORIGINAL LINE: void save(final android.media.Image image, String filename) internal virtual void save(Image image, string filename) { File dir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).AbsolutePath + "/Camera/"); if (!dir.exists()) { dir.mkdirs(); } //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final java.io.File file = new java.io.File(dir, filename); File file = new File(dir, filename); outerInstance.mBackgroundHandler.post(() => { ByteBuffer buffer = image.Planes[0].Buffer; sbyte[] bytes = new sbyte[buffer.remaining()]; buffer.get(bytes); System.IO.FileStream output = null; try { output = new System.IO.FileStream(file, System.IO.FileMode.Create, System.IO.FileAccess.Write); output.Write(bytes, 0, bytes.Length); } catch (IOException e) { Console.WriteLine(e.ToString()); Console.Write(e.StackTrace); } finally { image.close(); if (null != output) { try { output.Close(); } catch (IOException e) { Console.WriteLine(e.ToString()); Console.Write(e.StackTrace); } } } MediaScannerConnection.scanFile(outerInstance, new string[] { file.AbsolutePath }, null, new OnScanCompletedListenerAnonymousInnerClassHelper(this)); runOnUiThread(() => { Toast.makeTextuniquetempvar.show(); }); }); }
public void DeleteImageFromStorage(List <EOImgData> imageData) { foreach (EOImgData img in imageData) { Java.IO.File file = new Java.IO.File(img.fileName); file.Delete(); MediaScannerConnection.ScanFile(MainActivity.ActivityContext.ApplicationContext, new String[] { file.Path }, null, null); } imageData.Clear(); }
public virtual void ScanFile(string filePath) { try { MediaScannerConnection.ScanFile(Application.Context.ApplicationContext, new[] { filePath }, null, null); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine($"Exception when calling ScanFile: {ex.Message}"); // An exception because the scan failed should not cause a crash or even any problems with this app. // So, no need to throw the exception. Log it, move on. Nothing to see here. } }
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); } }
private void process(int type) { if (mInputImage == null) { Toast tempToast = Toast.makeText(Sample_Filter.this, "please select image.", Toast.LENGTH_SHORT); tempToast.show(); return; } string outputPath = mCameraDirectory + "/FILTER_IMAGE.jpg"; processFilter(mInputImage, outputPath, type); setImageView(mOutputImageView, outputPath); MediaScannerConnection.scanFile(this, new string[] { outputPath }, null, new OnScanCompletedListenerAnonymousInnerClassHelper(this)); }
public static void ExportData(Context context) { BackupInfo backupInfo = new BackupInfo(); backupInfo.Date = DateTime.Now; backupInfo.UniqueId = Guid.NewGuid(); backupInfo.DatabaseVersion = DatabaseHelper.GetVersion(context); backupInfo.PackageName = context.PackageName; try { backupInfo.AppVersionCode = context.ApplicationContext.PackageManager.GetPackageInfo(context.PackageName, 0).VersionCode; backupInfo.AppVersionName = context.ApplicationContext.PackageManager.GetPackageInfo(context.PackageName, 0).VersionName; } catch (Exception ex) { NLog.LogManager.GetCurrentClassLogger().Error(ex); } String backupInfoFileName = SaveBackupInfo(context, backupInfo); Java.IO.File file = new Java.IO.File(GlobalClass.GetLogDirectory(context)); List <String> logFilePaths = new List <string>(); if (file.Exists()) { Java.IO.File[] logFiles = file.ListFiles(new FileNameFilter()); foreach (Java.IO.File f in logFiles) { logFilePaths.Add(f.AbsolutePath); } } List <String> files = new List <string>(); files.Add(backupInfoFileName); foreach (var appId in VdmServiceHandler.GetAppIds(context)) { files.Add(DatabaseHelper.GetDatabaseFilePath(appId)); } files.AddRange(logFilePaths); string zipFilename = CreateBackupName(); Zip(context, files, zipFilename); String path = Path.Combine(context.ExternalCacheDir.AbsolutePath); MediaScannerConnection.ScanFile(context, new String[] { path }, null, null); }
partial void SaveImage(SurfaceSaver surfaceSaver, RenderTarget2D target) { var filename = $"output-{DateTime.Now:yyyyMMdd-HHmmss}.png"; var dir = AndroidEnvironment.GetExternalStoragePublicDirectory( AndroidEnvironment.DirectoryPictures).AbsolutePath; var path = Path.Combine(dir, filename); using (var stream = File.OpenWrite(path)) surfaceSaver.SaveAsPng(rtarget, stream); MediaScannerConnection.ScanFile(ApplicationContext, new String[] { path }, new String[] { MimeTypeMap.Singleton.GetMimeTypeFromExtension("png") }, null); confirmMsgText = $"Image saved to photo gallery"; confirmMsgOpacity = 1; }
public async Task <bool> SavePhotoAsnyc(byte[] data, string folder, string filename) { try { if (ContextCompat.CheckSelfPermission(MainActivity.Instance, Manifest.Permission.WriteExternalStorage) != PermissionChecker.PermissionGranted) { ActivityCompat.RequestPermissions(MainActivity.Instance, new string[] { Manifest.Permission.WriteExternalStorage }, 1000); } File picturesDirectory = Environment.GetExternalStoragePublicDirectory(Environment.DirectoryPictures); File folderDirectory; if (!string.IsNullOrEmpty(folder)) { folderDirectory = new File(picturesDirectory.ToString(), folder); folderDirectory.Mkdirs(); } else { folderDirectory = picturesDirectory; } using (File bitmapFile = new File("/storage/emulated/0/Download", filename)) { bitmapFile.CreateNewFile(); using (FileStream outputStream = new FileStream(bitmapFile.ToString(), FileMode.Open)) { await outputStream.WriteAsync(data); } // Make sure it shows up in the Photos gallery promptly. MediaScannerConnection.ScanFile(MainActivity.Instance, new string[] { bitmapFile.Path }, new string[] { "image/png", "image/jpeg" }, null); } } catch { return(false); } return(true); }
public void OnSuccess(string imagePath, Bitmap savedResultBitmap) { try { RunOnUiThread(() => { try { AndHUD.Shared.Dismiss(this); //wael //File pathOfFile = new File(imagePath); //MNiceArtEditorView.GetSource().SetImageURI(Uri.FromFile(pathOfFile)); //Show image in Gallery //var mediaScanIntent = new Intent(Intent.ActionMediaScannerScanFile); //mediaScanIntent.SetData(Uri.FromFile(pathOfFile)); //SendBroadcast(mediaScanIntent); // Tell the media scanner about the new file so that it is // immediately available to the user. MediaScannerConnection.ScanFile(this, new string[] { imagePath }, null, null); // put the String to pass back into an Intent and close this activity var resultIntent = new Intent(); resultIntent.PutExtra("ImagePath", imagePath); resultIntent.PutExtra("ImageId", IdImage); SetResult(Result.Ok, resultIntent); Finish(); MNiceArtEditor.ClearAllViews(); MNiceArtEditorView.GetSource().ClearColorFilter(); } catch (Exception e) { Console.WriteLine(e); } }); } catch (Exception e) { AndHUD.Shared.Dismiss(this); Console.WriteLine(e); } }