Я создаю растровое изображение, комбинируя два изображения. Теперь я пытаюсь сохранить его, сохранить, посмотреть и использовать в приложении.
Вот как я создаю свое новое растровое изображение:
string OnePath = "backgroundimage";
string TwoPath = "objectimage";
var OneImage = BitmapFactory.DecodeResource(Resources, Resources.GetIdentifier(OnePath, "drawable", PackageName));
var TwoImage = BitmapFactory.DecodeResource(Resources, Resources.GetIdentifier(TwoPath, "mipmap", PackageName));
Bitmap bitmap = OneImage.Copy(Bitmap.Config.Argb8888, true);
Canvas canvas = new Canvas(bitmap);
Rect baseRect = new Rect(0, 0, OneImage.Width, OneImage.Height);
Rect frontRect = new Rect(22, 31, 79, 79);
canvas.DrawBitmap(TwoImage, frontRect, baseRect, null);
Итак, теперь я хочу сохранить это новое растровое изображение, которое я создал. Я пытался сделать следующее:
var documentsDirectory = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
string jpgFilename = System.IO.Path.Combine(documentsDirectory, OnePath);
App.AppFileName = System.IO.Path.Combine(documentsDirectory, OnePath);
System.Diagnostics.Debug.WriteLine(App.AppFileName);
Где App.AppFileName - это строка, в которой хранится путь к изображению. Теперь я не уверен, действительно ли созданное изображение сохраняется там. Если я открываю файловый менеджер Android с телефоном Android, подключенным к моему компьютеру, я не вижу изображения в пути App.AppFileName.
@ user2912553 как я могу сохранить его на внешнем хранилище? Я хочу видеть изображение, не создавая его в приложении
Используйте Android.OS.Environment.ExternalStorageDir. Вы также должны убедиться, что ваш пакет имеет разрешение WRITE_EXTERNAL_STORAGE.
Поскольку изображение - это большой файл, я предлагаю вам сохранить его на внешнем хранилище Здесь вы можете узнать, что такое внешнее хранилище, по пути вроде: /storage/sdcard/Pictures, я сделал для вас демо:
using Android.App;
using Android.Widget;
using Android.OS;
using Android.Util;
using Android.Graphics;
using System.IO;
namespace SaveBitmap
{
[Activity(Label = "SaveBitmap", MainLauncher = true)]
public class MainActivity : Activity
{
string bitmapPath;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
bitmapPath = getPath("bitmap.png");
Bitmap bitmap = BitmapFactory.DecodeResource(Resources, Resource.Drawable.capture);
//save bitamp
saveBitmap(bitmap);
ImageView iv = FindViewById<ImageView>(Resource.Id.iv);
//load bitmap
Bitmap bi = BitmapFactory.DecodeFile(bitmapPath);
iv.SetImageBitmap(bi);
}
public string getPath(string fileName) {
var sdCardPath = Environment.GetExternalStoragePublicDirectory(Environment.DirectoryPictures);
Log.Error("lv", sdCardPath.AbsolutePath);
string filePath = System.IO.Path.Combine(sdCardPath.AbsolutePath, fileName);
return filePath;
}
public void saveBitmap(Bitmap bitmap ) {
FileStream stream = new FileStream(bitmapPath, FileMode.Create);
bitmap.Compress(Bitmap.CompressFormat.Png, 100, stream);
stream.Close();
}
}
}
Не забудьте добавить это в свой манифест:
<uses-permission android:name = "android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name = "android.permission.WRITE_EXTERNAL_STORAGE" />
Если вы запускаете приложение на более поздней версии Android 6.0, вам потребуется разрешение на выполнение.
Я добавил разрешение на выполнение.
using Android.App;
using Android.Widget;
using Android.OS;
using Android.Util;
using Android.Graphics;
using System.IO;
using System;
using Android;
using Android.Content.PM;
using Android.Runtime;
namespace SaveBitmap
{
[Activity(Label = "SaveBitmap", MainLauncher = true)]
public class MainActivity : Activity
{
string bitmapPath;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
bitmapPath = getPath("bitmap.png");
permissionCheck();
}
private void permissionCheck()
{
if (CheckSelfPermission(Manifest.Permission.ReadExternalStorage) != Permission.Granted)
{
// Should we show an explanation?
if (ShouldShowRequestPermissionRationale(Manifest.Permission.ReadExternalStorage))
{
// Show an expanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
}
else
{
// No explanation needed, we can request the permission.
RequestPermissions(new String[] { Manifest.Permission.ReadExternalStorage }, 1);
// MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
// app-defined int constant. The callback method gets the
// result of the request.
}
}
else {
saveAndLoadBitmap();
}
}
public string getPath(string fileName) {
var sdCardPath = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryPictures);
Log.Error("lv", sdCardPath.AbsolutePath);
string filePath = System.IO.Path.Combine(sdCardPath.AbsolutePath, fileName);
return filePath;
}
public void saveBitmap(Bitmap bitmap ) {
FileStream stream = new FileStream(bitmapPath, FileMode.Create);
bitmap.Compress(Bitmap.CompressFormat.Png, 100, stream);
stream.Close();
}
public void saveAndLoadBitmap() {
Bitmap bitmap = BitmapFactory.DecodeResource(Resources, Resource.Drawable.capture);
saveBitmap(bitmap);
ImageView iv = FindViewById<ImageView>(Resource.Id.iv);
Bitmap bi = BitmapFactory.DecodeFile(bitmapPath);
iv.SetImageBitmap(bi);
}
public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Permission[] grantResults)
{
switch (requestCode)
{
case 1:
{
// If request is cancelled, the result arrays are empty.
if (grantResults.Length > 0 && grantResults[0] == Permission.Granted)
{
// permission was granted, yay! Do the
// contacts-related task you need to do.
saveAndLoadBitmap();
}
else
{
// permission denied, boo! Disable the
// functionality that depends on this permission.
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
}
}
Ни одно другое приложение не может просматривать папку данных и открывать данные приложения, если вы не предоставите ему права root. Пожалуйста, проверьте это или сохраните изображение на внешнем хранилище.