public string DecriptFile(string filename, string name) { Java.IO.File extStore = Android.OS.Environment.GetExternalStoragePublicDirectory("Temp"); Android.Util.Log.Error("Decryption Started", extStore + ""); FileInputStream fis = new FileInputStream(extStore + "/" + filename); // createFile(filename, extStore); FileOutputStream fos = new FileOutputStream(extStore + "/" + "decrypted" + filename, false); System.IO.FileStream fs = System.IO.File.OpenWrite(extStore + "/" + name); Cipher cipher = Cipher.GetInstance("AES/CBC/PKCS5Padding"); byte[] raw = System.Text.Encoding.Default.GetBytes(sKey); SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); IvParameterSpec iv = new IvParameterSpec(System.Text.Encoding.Default.GetBytes(ivParameter));// cipher.Init(CipherMode.DecryptMode, skeySpec, iv); CipherOutputStream cos = new CipherOutputStream(fs, cipher); int b; byte[] d = new byte[1024 * 1024]; while ((b = fis.Read(d)) != -1) { cos.Write(d, 0, b); } System.IO.File.Delete(extStore + "/" + "decrypted" + filename); Android.Util.Log.Error("Decryption Ended", extStore + "/" + "decrypted" + name); return(extStore.ToString()); //return d; }
public string GetDirectory() { //string documentsPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments); // Documents folder File picturesDirectory = Environment.GetExternalStoragePublicDirectory(Environment.DirectoryPictures); return(picturesDirectory.ToString()); }
/// <summary> /// decode这个图片并且按比例缩放以减少内存消耗,虚拟机对每张图片的缓存大小也是有限制的 /// </summary> /// <returns>The file.</returns> /// <param name="f">F.</param> private Bitmap DecodeFile(Java.IO.File f) { try { //decode image size BitmapFactory.Options o = new BitmapFactory.Options(); o.InJustDecodeBounds = true; //FileInputStream stream1=new FileInputStream(f); FileStream stream1 = new FileStream(f.ToString(), FileMode.OpenOrCreate); BitmapFactory.DecodeStream(stream1, null, o); stream1.Close(); //Find the correct scale value. It should be the power of 2. int REQUIRED_SIZE = 60; int width_tmp = o.OutWidth, height_tmp = o.OutHeight; int scale = 1; while (true) { if (width_tmp / 2 < REQUIRED_SIZE || height_tmp / 2 < REQUIRED_SIZE) { break; } width_tmp /= 2; height_tmp /= 2; scale *= 2; } //decode with inSampleSize BitmapFactory.Options o2 = new BitmapFactory.Options(); o2.InSampleSize = scale; //FileInputStream stream2=new FileInputStream(f); FileStream stream2 = new FileStream(f.ToString(), FileMode.OpenOrCreate); Bitmap bitmap = BitmapFactory.DecodeStream(stream2, null, o2); stream2.Close(); return(bitmap); } catch (Java.IO.FileNotFoundException e) { e.PrintStackTrace(); } catch (Java.IO.IOException e) { e.PrintStackTrace(); } return(null); }
public string SafeHTMLToPDF(string html, string filename, int flag) { int width = 0; int height = 0; Android.Webkit.WebView webpage = null; var dir = new Java.IO.File(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath + "/KegIdFiles/"); 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"); } if (webpage == null) { webpage = new Android.Webkit.WebView(CrossCurrentActivity.Current.AppContext); } if (flag == 0) { width = 2959; height = 3873; } else { width = 3659; height = 4573; } webpage.Layout(0, 0, width, height); webpage.LoadDataWithBaseURL("", html, "text/html", "UTF-8", null); webpage.SetWebViewClient(new WebViewCallBack(file.ToString(), flag)); return(file.ToString()); }
public override void OnActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == (int)Result.Canceled) { return; } if (requestCode == None) { return; } if (requestCode == PhotoTake) { if (resultCode != (int)Result.Ok) { return; } //拍照 Java.IO.File picture = new Java.IO.File(Android.OS.Environment.ExternalStorageDirectory.ToString() + "/" + Android.OS.Environment.DirectoryDcim.ToString() + "/head.jpg"); if (System.IO.File.Exists(picture.ToString())) { CropPhoto(Android.Net.Uri.FromFile(picture)); } } if (data == null) { return; } if (requestCode == PhotoPick) //选取照片 { if (resultCode != (int)Result.Ok) { return; } CropPhoto(data.Data); } //处理结果 if (requestCode == PhotoResult) { Bundle extras = data.Extras; if (extras != null) { Bitmap photo = (Bitmap)extras.GetParcelable("data"); img_head.SetImageBitmap(photo); //将图像保存至本地和服务器上 SetPicToLocalAndServer(photo); //保存在SD卡中 } } base.OnActivityResult(requestCode, resultCode, data); }
public void Create(byte[] imageData) { var webClient = new WebClient(); //byte[] imageData = webClient.DownloadData("https://kasikornbank.com/SiteCollectionDocuments/about/img/logo/logo.png"); var resizeFactor = 0.5f; var bitmap = SKBitmap.Decode(imageData); var toBitmap = new SKBitmap((int)Math.Round(bitmap.Width * resizeFactor), (int)Math.Round(bitmap.Height * resizeFactor), bitmap.ColorType, bitmap.AlphaType); var canvas = new SKCanvas(toBitmap); canvas.SetMatrix(SKMatrix.MakeScale(resizeFactor, resizeFactor)); canvas.DrawBitmap(bitmap, 0, 0); canvas.ResetMatrix(); var font = SKTypeface.FromFamilyName("Arial"); var brush = new SKPaint { Typeface = font, TextSize = 64.0f, IsAntialias = true, Color = new SKColor(255, 255, 255, 255) }; canvas.DrawText("Resized!", 0, bitmap.Height * resizeFactor / 2.0f, brush); canvas.Flush(); var image = SKImage.FromBitmap(toBitmap); var data = image.Encode(SKEncodedImageFormat.Png, 90); DateTime now = DateTime.Now; string fileName = "Test"; //string fileName = ("{0}_{1}_{2}-{4}{5}{6}", now.Date,now.Month,now.Year,now.Hour,now.Minute,now.Second).ToString(); string extension = ".png"; Java.IO.File picturesDirectory = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryPictures); Java.IO.File folderDirectory = picturesDirectory; //Start Save using (var stream = new FileStream(Path.Combine(folderDirectory.ToString(), fileName + extension), FileMode.Create, FileAccess.Write)) data.SaveTo(stream); //End Save data.Dispose(); image.Dispose(); canvas.Dispose(); brush.Dispose(); font.Dispose(); toBitmap.Dispose(); bitmap.Dispose(); }
private void Save(string windowname) { if (windowname != "") { try { Java.IO.File path = new Java.IO.File(App._dir, windowname); if (!path.Exists()) { path.Mkdirs(); } else { MessageBox.Confirm(this, "警告", "该文件夹已存在,是否覆盖?", delegate { path.Mkdirs(); }, delegate { }); } SavePics(path.ToString()); SaveResult.SaveGeologicalData(path.ToString()); SaveResult.SaveGeometricalData(path.ToString()); SaveResult.SaveStatisticalResult(path.ToString()); MessageBox.Show(this, "成功", "保存成功"); } catch { MessageBox.Show(this, "失败", "保存失败"); } } else { MessageBox.Show(this, "注意", "测窗名称不能为空!"); } }
public string GetScanPath() { File ExtCameraDirectory = new File(Environment.GetExternalStoragePublicDirectory(Environment.DirectoryDcim), "Camera"); File Ext100ANDRODirectory = new File(Environment.GetExternalStoragePublicDirectory(Environment.DirectoryDcim), "100ANDRO"); if (Ext100ANDRODirectory.ListFiles().Length == 0) { return(ExtCameraDirectory.ToString()); } else { return(Ext100ANDRODirectory.ToString()); } }
public static string getSDPath() { Java.IO.File sdDir = null; bool sdCardExist = Android.OS.Environment.ExternalStorageState.Equals(Android.OS.Environment.MediaMounted); // 判断sd卡是否存在 if (sdCardExist) { sdDir = Android.OS.Environment.ExternalStorageDirectory; // 获取跟目录 } if (sdDir != null) { return(sdDir.ToString()); } return(null); }
public static void addImageToGallery(File filePath, Context context, Camera2BasicFragment owner) { try { var fileName = System.IO.Path.GetFileName(filePath.Path); var publicUri = MainActivity.GetOutputMediaFile(context, null, null); if (publicUri == null) { owner.ShowToast("File could not be saved. Please grant permission to write to external storage."); return; } using (System.IO.Stream input = System.IO.File.OpenRead(filePath.Path)) using (System.IO.Stream output = System.IO.File.Create(publicUri.Path)) input.CopyTo(output); var f = new Java.IO.File(publicUri.Path); Android.Media.MediaScannerConnection.ScanFile(context, new[] { f.AbsolutePath }, null, context as MainActivity); ContentValues values = new ContentValues(); values.Put(MediaStore.Images.Media.InterfaceConsts.Title, System.IO.Path.GetFileNameWithoutExtension(f.AbsolutePath)); 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, f.ToString().ToLowerInvariant().GetHashCode()); values.Put(MediaStore.Images.ImageColumns.BucketDisplayName, f.Name.ToLowerInvariant()); values.Put("_data", f.AbsolutePath); var cr = context.ContentResolver; var uri = cr.Insert(MediaStore.Images.Media.ExternalContentUri, values); var contentUri = uri; var mediaScanIntent = new Intent(Intent.ActionMediaScannerScanFile, contentUri); mediaScanIntent.SetData(contentUri); context.SendBroadcast(mediaScanIntent); } catch (Exception) { // Console.WriteLine("Unable to save to scan file: " + ex1); } }
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 OnPictureTaken(byte[] data, Camera camera) { Java.IO.File ExternalStorageUserRootFolder; Java.IO.File ImageFolderExternalStorage; try { // Obtém o caminho da pasta raiz do aplicativo ExternalStorageUserRootFolder = new Java.IO.File(Android.OS.Environment.ExternalStorageDirectory + Java.IO.File.Separator + "SeeLocker"); // Obtém oc aminho da pasta de imagens do aplicativo var strImagePath = ExternalStorageUserRootFolder.ToString() + Java.IO.File.Separator + "Images"; // Se a pasta de iamgens não existe if (!System.IO.Directory.Exists(strImagePath)) { // Cria a pasta de imagens ImageFolderExternalStorage = new Java.IO.File(strImagePath); ImageFolderExternalStorage.Mkdirs(); } Android.Graphics.Bitmap bitmapPicture = Android.Graphics.BitmapFactory.DecodeByteArray(data, 0, data.Length); bitmapPictureBackup = Android.Graphics.BitmapFactory.DecodeByteArray(data, 0, data.Length); String PhotoName = String.Format("{0}.jpg", Guid.NewGuid()); System.IO.Stream fos = new System.IO.FileStream(strImagePath + "/" + PhotoName, System.IO.FileMode.Create); bitmapPicture.Compress(Android.Graphics.Bitmap.CompressFormat.Jpeg, 50, fos); fos.Flush(); fos.Close(); bitmapPicture.Dispose(); //Toast.MakeText(Application.Context, "Success", ToastLength.Long).Show(); } catch (Exception ex) { } finally { camera.StartPreview(); } }
private void writeInStorage(String fileName, String TEXT) { bool test; Context sContext = Android.App.Application.Context; try { Java.IO.File dirv = new Java.IO.File(Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDocuments).AbsolutePath + "/AndroidTest/" + fileName + ".txt"); Java.IO.File path = new Java.IO.File(Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDocuments).AbsolutePath + "/AndroidTest");; if (!path.Exists()) { path.Mkdirs(); } //Java.IO.File dirv = new Java.IO.File("/storage/emulated/AndroidTest"); if (!dirv.Exists())//工作目录是否存在? { test = dirv.CreateNewFile(); } FileStream fileOS = new FileStream(dirv.ToString(), System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write); //String str = "this is a test about Write SD card file"; Java.IO.BufferedWriter buf1 = new Java.IO.BufferedWriter(new Java.IO.OutputStreamWriter(fileOS)); buf1.Write(TEXT, 0, TEXT.Length); buf1.Flush(); buf1.Close(); fileOS.Close(); Toast.MakeText(sContext, "写入完成", ToastLength.Short).Show(); } catch (Java.IO.FileNotFoundException e) { Toast.MakeText(sContext, e.ToString(), ToastLength.Short).Show(); } catch (UnsupportedEncodingException e) { Toast.MakeText(sContext, e.ToString(), ToastLength.Short).Show(); } catch (Java.IO.IOException e) { Toast.MakeText(sContext, e.ToString(), ToastLength.Short).Show(); } }
private void SaveOutput(Bitmap croppedImage) { if (this.SaveUri != null) { Stream outputStream = null; try { outputStream = ContentResolver.OpenOutputStream(this.SaveUri); if (outputStream != null) { croppedImage.Compress(this.OutputFormat, this.OutputQuality, outputStream); } } catch (System.IO.IOException ex) { System.Diagnostics.Debug.WriteLine("Cannot open file {0} {1}", this.SaveUri, ex); } finally { outputStream.Close(); // try catch? } Bundle extras = new Bundle(); this.SetResult(Result.Ok, new Intent(this.SaveUri.ToString()).PutExtras(extras)); } else { Bundle extras = new Bundle(); extras.PutString("rect", this.MCrop.GetCropRect().ToString()); Java.IO.File oldPath = new Java.IO.File(this.Image.DataPath); Java.IO.File directory = new Java.IO.File(oldPath.Parent); int x = 0; string fileName = oldPath.Name; fileName = fileName.Substring(0, fileName.LastIndexOf(".")); // Try file-1.jpg, file-2.jpg, ... until we find a filename which // does not exist yet. while (true) { x += 1; string candidate = directory.ToString() + "/" + fileName + "-" + x + ".jpg"; bool exists = (new Java.IO.File(candidate)).Exists(); if (!exists) { break; } } try { int[] degree = new int [1]; Android.Net.Uri newUri = ImageManager.AddImage(ContentResolver, this.Image.Title, this.Image.DateTaken, null, directory.ToString(), fileName + "-" + x + ".jpg", croppedImage, null, degree); this.SetResult(Result.Ok, new Intent().SetAction(newUri.ToString()).PutExtras(extras)); } catch (Java.Lang.Exception ex) { // basically ignore this or put up // some ui saying we failed System.Diagnostics.Debug.WriteLine("storge image fail, continue anyway {0}", ex); } } Bitmap b = croppedImage; this.MHandler.Post(() => { this.ImageView.Clear(); b.Recycle(); }); this.Finish(); }
/** * Tests extraction from an MP4 to a series of PNG files. * <p> * We scale the video to 640x480 for the PNG just to demonstrate that we can scale the * video with the GPU. If the input video has a different aspect ratio, we could preserve * it by adjusting the GL viewport to get letterboxing or pillarboxing, but generally if * you're extracting frames you don't want black bars. */ public void extractMpegFrames(int saveWidth, int saveHeight) { MediaCodec decoder = null; CodecOutputSurface outputSurface = null; MediaExtractor extractor = null; try { // must be an absolute path The MediaExtractor error messages aren't very useful. Check to see if the input file exists so we can throw a better one if it's not there. File inputFile = new File(_filesdir, INPUT_FILE); if (!inputFile.CanRead()) { throw new FileNotFoundException("Unable to read " + inputFile); } extractor = new MediaExtractor(); extractor.SetDataSource(inputFile.ToString()); int trackIndex = selectTrack(extractor); if (trackIndex < 0) { throw new RuntimeException("No video track found in " + inputFile); } extractor.SelectTrack(trackIndex); MediaFormat format = extractor.GetTrackFormat(trackIndex); if (VERBOSE) { Log.Info(TAG, "Video size is " + format.GetInteger(MediaFormat.KeyWidth) + "x" + 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, outputSurface.getSurface(), null, 0); decoder.Start(); doExtract(extractor, trackIndex, decoder, outputSurface); } 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; } } }
private string GetCardPath() { Java.IO.File sdDir = Android.OS.Environment.ExternalStorageDirectory;//获取手机根目录 return(sdDir.ToString()); }
public override void OnActivityResult (int requestCode, int resultCode, Intent data) { if (resultCode == (int)Result.Canceled) return; if (requestCode == None) return; if (requestCode == PhotoTake) { if (resultCode !=(int) Result.Ok) return; //拍照 Java.IO.File picture = new Java.IO.File(Android.OS.Environment.ExternalStorageDirectory.ToString()+"/"+Android.OS.Environment.DirectoryDcim.ToString() + "/head.jpg"); if (System.IO.File.Exists(picture.ToString())) { CropPhoto(Android.Net.Uri.FromFile(picture)); } } if (data == null) return; if (requestCode == PhotoPick) {//选取照片 if (resultCode != (int)Result.Ok) return; CropPhoto(data.Data); } //处理结果 if (requestCode == PhotoResult) { Bundle extras = data.Extras; if (extras != null) { Bitmap photo = (Bitmap)extras.GetParcelable("data"); img_head.SetImageBitmap (photo); //将图像保存至本地和服务器上 SetPicToLocalAndServer(photo);//保存在SD卡中 } } base.OnActivityResult (requestCode, resultCode, data); }
//public static void ShowOkAlert(Context context,string Message) //{ // AlertDialog.Builder alert = new AlertDialog.Builder(context); // alert.SetMessage(Message); // alert.SetPositiveButton("Ok", (senderAlert, args) => { // }); // Dialog dialog = alert.Create(); // dialog.Show(); //} //Download from url------------------------------------------ public static async void DownLoadSource(string url, Java.IO.File _appDirectory, Java.IO.File newFile, string filePath, Context context, string FileName, int notificationId) { // ShowToast(context, context.Resources.GetString(Resource.String.downloading) + Newsrc); var NotificationId = notificationId; string localPath; try { System.Uri uri = new System.Uri(url); WebClient webClient = new WebClient(); string localFileName; webClient.DownloadDataAsync(uri); Log.Debug("tag", "File to download = " + newFile.ToString()); MimeTypeMap mime = MimeTypeMap.Singleton; String ext = newFile.Name.Substring(newFile.Name.IndexOf(".") + 1); String type = mime.GetMimeTypeFromExtension(ext); Intent openFile = new Intent(Intent.ActionView, Android.Net.Uri.FromFile(newFile)); openFile.SetDataAndType(Android.Net.Uri.FromFile(newFile), type); openFile.AddFlags(ActivityFlags.ClearTop | ActivityFlags.SingleTop | ActivityFlags.NewTask); PendingIntent p = PendingIntent.GetActivity(context, 0, openFile, 0); var notification = new Android.Support.V4.App.NotificationCompat.Builder(context) .SetSmallIcon(Android.Resource.Drawable.StatNotifySync) .SetContentTitle(FileName) .SetContentText(" Downloading") .SetOngoing(false); notification.SetProgress(0, 0, true); NotificationManager notificationmanager = (NotificationManager)Android.App.Application.Context.GetSystemService(Service.NotificationService); // Build Notification with Notification Manager notificationmanager.Notify((int)NotificationId, notification.Build()); webClient.DownloadDataCompleted += (s, e) => { try { if (!_appDirectory.Exists()) { _appDirectory.Mkdirs(); } var bytes = e.Result; // get the downloaded data { notification.SetContentText(" Downloaded"); notification.SetContentTitle(FileName); notification.SetContentIntent(p); notification.SetProgress(0, 0, false); notification.SetAutoCancel(true);// Notification.Flags = NotificationFlags.AutoCancel; //System.IO.File.WriteAllBytes(filePath, bytes); notificationmanager.Notify((int)NotificationId, notification.Build()); // writes to local storage } } catch (Exception ex) { } }; } catch (System.Exception ex) { } }