如何将视图转换为位图并另存为图像? [英] How to convert views to bitmap and save as Image?

查看:68
本文介绍了如何将视图转换为位图并另存为图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将视图转换为位图并另存为图像!我找到了一些方法来执行此操作,但在Android 10或更高版本中不起作用!

I am trying to convert views to bitmap and save as image! I found some method to do that but it doesn't work in Android 10 or higher version!

这是我的XML代码:-

Here is my XML code:-

    <?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <LinearLayout
        android:id="@+id/layout1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="20dp"
        android:background="@color/teal_200"
        android:gravity="center"
        android:orientation="horizontal"
        app:layout_constraintBottom_toTopOf="@+id/btnSaveID"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/kohli" />

    </LinearLayout>

    <Button
        android:id="@+id/btnSaveID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="30dp"
        android:paddingLeft="50dp"
        android:paddingRight="50dp"
        android:text="@string/save"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/layout1" />

</androidx.constraintlayout.widget.ConstraintLayout>

这是我的Java代码:-

and Here is my Java Code:-

public class MainActivity extends AppCompatActivity {
    LinearLayout layout;
    OutputStream outputStream;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        layout = findViewById(R.id.layout1);


        findViewById(R.id.btnSaveID).setOnClickListener(v -> {

            if (Build.VERSION.SDK_INT >= 23) {
                String requiredPermission = Manifest.permission.READ_EXTERNAL_STORAGE;
                int checkVal = checkCallingOrSelfPermission(requiredPermission);

                if (checkVal == PackageManager.PERMISSION_GRANTED) {
                    saveImage2(layout);

                } else {
                    checkPermission(layout);
                }
            } else {
                saveImage2(layout);

            }
        });

    }

    private void saveImage2(LinearLayout layout1) {
        layout1.setDrawingCacheEnabled(true);
        layout1.buildDrawingCache();
        Bitmap bitmap = Bitmap.createBitmap(layout1.getWidth(), layout1.getHeight(), Bitmap.Config.ARGB_8888);
        if (bitmap != null) {
            Canvas canvas = new Canvas(bitmap);
            layout1.draw(canvas);

            Drawable bgDrawable = layout1.getBackground();

            if (bgDrawable != null) {
                bgDrawable.draw(canvas);
            } else {
                canvas.drawColor(Color.WHITE);
            }

            layout1.draw(canvas);

            String folderName = "/VIRAT kOLI/";
            File dir = new File(Environment.getExternalStorageDirectory() + File.separator + folderName);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            File file = new File(dir, System.currentTimeMillis() + ".png");
            try {
                outputStream = new FileOutputStream(file);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
            try {
                outputStream.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

            String xy = file.getAbsolutePath();
            MediaScannerConnection.scanFile(MainActivity.this, new String[]{xy}, new String[]{"image/*"},
                    new MediaScannerConnection.MediaScannerConnectionClient() {
                        public void onMediaScannerConnected() {
                        }

                        public void onScanCompleted(String path, Uri uri) {
                        }
                    });

            Toast.makeText(MainActivity.this, "Saved to" + file.getAbsolutePath(), Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(MainActivity.this, "Unable to download now! This feature coming soon.", Toast.LENGTH_SHORT).show();
        }
    }

    private void checkPermission(LinearLayout layout) {
        PermissionListener permissionListener = new PermissionListener() {
            @Override
            public void onPermissionGranted() {
                saveImage2(layout);
            }

            @Override
            public void onPermissionDenied(List<String> deniedPermissions) {
                Toast.makeText(MainActivity.this, "Permission required to download", Toast.LENGTH_SHORT).show();
            }
        };

        TedPermission.with(MainActivity.this)
                .setPermissionListener(permissionListener)
                .setPermissions(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .check();
    }

}

以下是清单文件代码:-

Here is the Manifests file code:-

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.noobprogroammer.sampleproject">

    <uses-permission
        android:name="android.permission.WRITE_EXTERNAL_STORAGE"
        tools:ignore="ScopedStorage" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:requestLegacyExternalStorage="true"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.SAMPLEPROJECT">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <provider
            android:name="androidx.core.content.FileProvider"
            android:authorities="com.noobprogroammer.sampleproject.fileprovider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_paths" />
        </provider>
    </application>

</manifest>

我添加了如下的自定义文件路径:-

I have added the custom file path as follows:-

<?xml version="1.0" encoding="utf-8"?>
<paths>
    <external-path
        name="external_files"
        path="." />
</paths>

任何人都可以检查我的代码吗?如前所述,它无法在Android 10及更高版本中运行,并出现 NullPointerException

Can anyone check my code? As mentioned earlier, it's not working in Android 10 and higher, failing with NullPointerException

推荐答案

使用此方法.它将位图保存到Pictures文件夹(MediaStore API)

Use this method. It will save bitmap to Pictures folder (MediaStore API)

还了解有关范围存储

    public static Uri savePng(Context context, Bitmap bitmap, @NonNull String name) throws IOException {
        Uri uri;
        OutputStream fileOutputStream;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            ContentResolver resolver = context.getContentResolver();
            ContentValues contentValues = new ContentValues();
            contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, name + ".png");
            contentValues.put(MediaStore.MediaColumns.MIME_TYPE, "image/png");
            contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_PICTURES);
            uri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
            fileOutputStream = resolver.openOutputStream(Objects.requireNonNull(uri));
        } else {
            String imagePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString();
            File image = new File(imagePath, name + ".png");
            fileOutputStream = new FileOutputStream(image);
            uri = getUriFromPath(context, imagePath);
        }
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream);
        fileOutputStream.close();
        return uri;
    }


    private static Uri getUriFromPath(Context context, String imagePath) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
            return FileProvider.getUriForFile(context, "com.noobprogroammer.sampleproject.fileProvider", new File(imagePath));
        return Uri.fromFile(new File(imagePath));
    }


    protected void openImage(Uri uri) {
        try {
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_VIEW);
            intent.setDataAndType(uri, "image/*");
            startActivity(intent);
        }catch (Exception e){
            Toast.makeText(this, "Error opening image", Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }
    }

这篇关于如何将视图转换为位图并另存为图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆