├── app
├── .gitignore
├── src
│ ├── main
│ │ ├── res
│ │ │ ├── values
│ │ │ │ ├── strings.xml
│ │ │ │ ├── themes.xml
│ │ │ │ └── colors.xml
│ │ │ ├── mipmap-hdpi
│ │ │ │ ├── ic_launcher.webp
│ │ │ │ └── ic_launcher_round.webp
│ │ │ ├── mipmap-mdpi
│ │ │ │ ├── ic_launcher.webp
│ │ │ │ └── ic_launcher_round.webp
│ │ │ ├── mipmap-xhdpi
│ │ │ │ ├── ic_launcher.webp
│ │ │ │ └── ic_launcher_round.webp
│ │ │ ├── mipmap-xxhdpi
│ │ │ │ ├── ic_launcher.webp
│ │ │ │ └── ic_launcher_round.webp
│ │ │ ├── mipmap-xxxhdpi
│ │ │ │ ├── ic_launcher.webp
│ │ │ │ └── ic_launcher_round.webp
│ │ │ ├── xml
│ │ │ │ ├── file_paths.xml
│ │ │ │ ├── backup_rules.xml
│ │ │ │ └── data_extraction_rules.xml
│ │ │ ├── mipmap-anydpi-v26
│ │ │ │ ├── ic_launcher.xml
│ │ │ │ └── ic_launcher_round.xml
│ │ │ ├── layout
│ │ │ │ └── activity_main.xml
│ │ │ └── drawable
│ │ │ │ ├── ic_launcher_foreground.xml
│ │ │ │ └── ic_launcher_background.xml
│ │ ├── java
│ │ │ └── portrait
│ │ │ │ └── bala
│ │ │ │ └── portrait
│ │ │ │ ├── ui
│ │ │ │ └── theme
│ │ │ │ │ ├── Color.kt
│ │ │ │ │ ├── Type.kt
│ │ │ │ │ └── Theme.kt
│ │ │ │ ├── App.java
│ │ │ │ ├── PermissionUtil.java
│ │ │ │ ├── MainActivity.java
│ │ │ │ └── FileUtil.java
│ │ └── AndroidManifest.xml
│ ├── test
│ │ └── java
│ │ │ └── portrait
│ │ │ └── bala
│ │ │ └── portrait
│ │ │ └── ExampleUnitTest.kt
│ └── androidTest
│ │ └── java
│ │ └── portrait
│ │ └── bala
│ │ └── portrait
│ │ └── ExampleInstrumentedTest.kt
├── proguard-rules.pro
└── build.gradle
├── .idea
├── .gitignore
├── compiler.xml
├── kotlinc.xml
├── vcs.xml
├── migrations.xml
├── misc.xml
├── deploymentTargetSelector.xml
├── gradle.xml
├── inspectionProfiles
│ └── Project_Default.xml
└── codeStyles
├── gradle
├── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
└── libs.versions.toml
├── .gitignore
├── settings.gradle
├── gradle.properties
├── gradlew.bat
└── gradlew
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
--------------------------------------------------------------------------------
/.idea/.gitignore:
--------------------------------------------------------------------------------
1 | # Default ignored files
2 | /shelf/
3 | /workspace.xml
4 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | BalaPortrait
3 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jiaweizeng/BalaPortrait/HEAD/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jiaweizeng/BalaPortrait/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jiaweizeng/BalaPortrait/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jiaweizeng/BalaPortrait/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jiaweizeng/BalaPortrait/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jiaweizeng/BalaPortrait/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jiaweizeng/BalaPortrait/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jiaweizeng/BalaPortrait/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jiaweizeng/BalaPortrait/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jiaweizeng/BalaPortrait/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jiaweizeng/BalaPortrait/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/.idea/compiler.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/app/src/main/res/values/themes.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/.idea/kotlinc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Wed Jul 03 17:45:26 CST 2024
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.7-bin.zip
5 | zipStoreBase=GRADLE_USER_HOME
6 | zipStorePath=wrapper/dists
7 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | /local.properties
4 | /.idea/caches
5 | /.idea/libraries
6 | /.idea/modules.xml
7 | /.idea/workspace.xml
8 | /.idea/navEditor.xml
9 | /.idea/assetWizardSettings.xml
10 | .DS_Store
11 | /build
12 | /captures
13 | .externalNativeBuild
14 | .cxx
15 | local.properties
16 |
--------------------------------------------------------------------------------
/.idea/migrations.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
9 |
10 |
--------------------------------------------------------------------------------
/app/src/main/res/xml/file_paths.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/app/src/main/java/portrait/bala/portrait/ui/theme/Color.kt:
--------------------------------------------------------------------------------
1 | package portrait.bala.portrait.ui.theme
2 |
3 | import androidx.compose.ui.graphics.Color
4 |
5 | val Purple80 = Color(0xFFD0BCFF)
6 | val PurpleGrey80 = Color(0xFFCCC2DC)
7 | val Pink80 = Color(0xFFEFB8C8)
8 |
9 | val Purple40 = Color(0xFF6650a4)
10 | val PurpleGrey40 = Color(0xFF625b71)
11 | val Pink40 = Color(0xFF7D5260)
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #FFBB86FC
4 | #FF6200EE
5 | #FF3700B3
6 | #FF03DAC5
7 | #FF018786
8 | #FF000000
9 | #FFFFFFFF
10 |
--------------------------------------------------------------------------------
/app/src/test/java/portrait/bala/portrait/ExampleUnitTest.kt:
--------------------------------------------------------------------------------
1 | package portrait.bala.portrait
2 |
3 | import org.junit.Test
4 |
5 | import org.junit.Assert.*
6 |
7 | /**
8 | * Example local unit test, which will execute on the development machine (host).
9 | *
10 | * See [testing documentation](http://d.android.com/tools/testing).
11 | */
12 | class ExampleUnitTest {
13 | @Test
14 | fun addition_isCorrect() {
15 | assertEquals(4, 2 + 2)
16 | }
17 | }
--------------------------------------------------------------------------------
/app/src/main/res/xml/backup_rules.xml:
--------------------------------------------------------------------------------
1 |
8 |
9 |
13 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | pluginManagement {
2 | repositories {
3 | google {
4 | content {
5 | includeGroupByRegex("com\\.android.*")
6 | includeGroupByRegex("com\\.google.*")
7 | includeGroupByRegex("androidx.*")
8 | }
9 | }
10 | mavenCentral()
11 | gradlePluginPortal()
12 | }
13 | }
14 | dependencyResolutionManagement {
15 | repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
16 | repositories {
17 | google()
18 | mavenCentral()
19 | }
20 | }
21 |
22 | rootProject.name = "BalaPortrait"
23 | include ':app'
24 |
--------------------------------------------------------------------------------
/app/src/main/res/xml/data_extraction_rules.xml:
--------------------------------------------------------------------------------
1 |
6 |
7 |
8 |
12 |
13 |
19 |
--------------------------------------------------------------------------------
/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
--------------------------------------------------------------------------------
/.idea/deploymentTargetSelector.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
--------------------------------------------------------------------------------
/.idea/gradle.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
--------------------------------------------------------------------------------
/app/src/main/java/portrait/bala/portrait/App.java:
--------------------------------------------------------------------------------
1 | package portrait.bala.portrait;
2 |
3 | import android.app.Application;
4 | import android.os.Build;
5 | import android.os.StrictMode;
6 |
7 | /**
8 | * Created by zjw on 2018/3/8 0008.
9 | */
10 |
11 | public class App extends Application {
12 | @Override
13 | public void onCreate() {
14 | super.onCreate();
15 | StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
16 | if (Build.VERSION.SDK_INT >= 18){
17 |
18 | builder.detectFileUriExposure();
19 | }
20 | StrictMode.setVmPolicy(builder.build());
21 | /* StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
22 | StrictMode.setVmPolicy(builder.build());*/
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/app/src/androidTest/java/portrait/bala/portrait/ExampleInstrumentedTest.kt:
--------------------------------------------------------------------------------
1 | package portrait.bala.portrait
2 |
3 | import androidx.test.platform.app.InstrumentationRegistry
4 | import androidx.test.ext.junit.runners.AndroidJUnit4
5 |
6 | import org.junit.Test
7 | import org.junit.runner.RunWith
8 |
9 | import org.junit.Assert.*
10 |
11 | /**
12 | * Instrumented test, which will execute on an Android device.
13 | *
14 | * See [testing documentation](http://d.android.com/tools/testing).
15 | */
16 | @RunWith(AndroidJUnit4::class)
17 | class ExampleInstrumentedTest {
18 | @Test
19 | fun useAppContext() {
20 | // Context of the app under test.
21 | val appContext = InstrumentationRegistry.getInstrumentation().targetContext
22 | assertEquals("portrait.bala.portrait", appContext.packageName)
23 | }
24 | }
--------------------------------------------------------------------------------
/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
--------------------------------------------------------------------------------
/app/src/main/java/portrait/bala/portrait/PermissionUtil.java:
--------------------------------------------------------------------------------
1 | package portrait.bala.portrait;
2 |
3 |
4 | /**
5 | * Created by zjw on 2023/12/26.
6 | */
7 | public class PermissionUtil {
8 |
9 | public static final String READ_MEDIA_IMAGES = "android.permission.READ_MEDIA_IMAGES";
10 | public static final String READ_EXTERNAL_STORAGE = "android.permission.READ_EXTERNAL_STORAGE";
11 |
12 | public static boolean isSdkInt33() {
13 | return getSdkInt() >= 33;
14 | }
15 |
16 | public static int getSdkInt() {
17 | return android.os.Build.VERSION.SDK_INT;
18 | }
19 |
20 | public static String getReadImgPermission() {
21 | String picPermission = PermissionUtil.READ_EXTERNAL_STORAGE;
22 | if (PermissionUtil.isSdkInt33()) {
23 | picPermission = PermissionUtil.READ_MEDIA_IMAGES;
24 | }
25 | return picPermission;
26 | }
27 |
28 | }
29 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
6 |
7 |
12 |
13 |
18 |
19 |
24 |
25 |
26 |
--------------------------------------------------------------------------------
/app/src/main/java/portrait/bala/portrait/ui/theme/Type.kt:
--------------------------------------------------------------------------------
1 | package portrait.bala.portrait.ui.theme
2 |
3 | import androidx.compose.material3.Typography
4 | import androidx.compose.ui.text.TextStyle
5 | import androidx.compose.ui.text.font.FontFamily
6 | import androidx.compose.ui.text.font.FontWeight
7 | import androidx.compose.ui.unit.sp
8 |
9 | // Set of Material typography styles to start with
10 | val Typography = Typography(
11 | bodyLarge = TextStyle(
12 | fontFamily = FontFamily.Default,
13 | fontWeight = FontWeight.Normal,
14 | fontSize = 16.sp,
15 | lineHeight = 24.sp,
16 | letterSpacing = 0.5.sp
17 | )
18 | /* Other default text styles to override
19 | titleLarge = TextStyle(
20 | fontFamily = FontFamily.Default,
21 | fontWeight = FontWeight.Normal,
22 | fontSize = 22.sp,
23 | lineHeight = 28.sp,
24 | letterSpacing = 0.sp
25 | ),
26 | labelSmall = TextStyle(
27 | fontFamily = FontFamily.Default,
28 | fontWeight = FontWeight.Medium,
29 | fontSize = 11.sp,
30 | lineHeight = 16.sp,
31 | letterSpacing = 0.5.sp
32 | )
33 | */
34 | )
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 | # IDE (e.g. Android Studio) users:
3 | # Gradle settings configured through the IDE *will override*
4 | # any settings specified in this file.
5 | # For more details on how to configure your build environment visit
6 | # http://www.gradle.org/docs/current/userguide/build_environment.html
7 | # Specifies the JVM arguments used for the daemon process.
8 | # The setting is particularly useful for tweaking memory settings.
9 | org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
10 | # When configured, Gradle will run in incubating parallel mode.
11 | # This option should only be used with decoupled projects. For more details, visit
12 | # https://developer.android.com/r/tools/gradle-multi-project-decoupled-projects
13 | # org.gradle.parallel=true
14 | # AndroidX package structure to make it clearer which packages are bundled with the
15 | # Android operating system, and which are packaged with your app's APK
16 | # https://developer.android.com/topic/libraries/support-library/androidx-rn
17 | android.useAndroidX=true
18 | # Kotlin code style for this project: "official" or "obsolete":
19 | kotlin.code.style=official
20 | # Enables namespacing of each library's R class so that its R class includes only the
21 | # resources declared in the library itself and none from the library's dependencies,
22 | # thereby reducing the size of the R class for that library
23 | android.nonTransitiveRClass=true
24 | android.injected.testOnly=false
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_launcher_foreground.xml:
--------------------------------------------------------------------------------
1 |
7 |
8 |
9 |
15 |
18 |
21 |
22 |
23 |
24 |
30 |
--------------------------------------------------------------------------------
/app/src/main/java/portrait/bala/portrait/ui/theme/Theme.kt:
--------------------------------------------------------------------------------
1 | package portrait.bala.portrait.ui.theme
2 |
3 | import android.app.Activity
4 | import android.os.Build
5 | import androidx.compose.foundation.isSystemInDarkTheme
6 | import androidx.compose.material3.MaterialTheme
7 | import androidx.compose.material3.darkColorScheme
8 | import androidx.compose.material3.dynamicDarkColorScheme
9 | import androidx.compose.material3.dynamicLightColorScheme
10 | import androidx.compose.material3.lightColorScheme
11 | import androidx.compose.runtime.Composable
12 | import androidx.compose.ui.platform.LocalContext
13 |
14 | private val DarkColorScheme = darkColorScheme(
15 | primary = Purple80,
16 | secondary = PurpleGrey80,
17 | tertiary = Pink80
18 | )
19 |
20 | private val LightColorScheme = lightColorScheme(
21 | primary = Purple40,
22 | secondary = PurpleGrey40,
23 | tertiary = Pink40
24 |
25 | /* Other default colors to override
26 | background = Color(0xFFFFFBFE),
27 | surface = Color(0xFFFFFBFE),
28 | onPrimary = Color.White,
29 | onSecondary = Color.White,
30 | onTertiary = Color.White,
31 | onBackground = Color(0xFF1C1B1F),
32 | onSurface = Color(0xFF1C1B1F),
33 | */
34 | )
35 |
36 | @Composable
37 | fun BalaPortraitTheme(
38 | darkTheme: Boolean = isSystemInDarkTheme(),
39 | // Dynamic color is available on Android 12+
40 | dynamicColor: Boolean = true,
41 | content: @Composable () -> Unit
42 | ) {
43 | val colorScheme = when {
44 | dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
45 | val context = LocalContext.current
46 | if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
47 | }
48 |
49 | darkTheme -> DarkColorScheme
50 | else -> LightColorScheme
51 | }
52 |
53 | MaterialTheme(
54 | colorScheme = colorScheme,
55 | typography = Typography,
56 | content = content
57 | )
58 | }
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
8 |
20 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
37 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | plugins {
2 | alias(libs.plugins.android.application)
3 | alias(libs.plugins.jetbrains.kotlin.android)
4 | }
5 |
6 | android {
7 | namespace 'portrait.bala.portrait'
8 | compileSdk 34
9 |
10 | defaultConfig {
11 | applicationId "portrait.bala.portrait"
12 | minSdk 24
13 | targetSdk 34
14 | versionCode 1
15 | versionName "1.0"
16 |
17 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
18 | vectorDrawables {
19 | useSupportLibrary true
20 | }
21 | }
22 |
23 | buildTypes {
24 | release {
25 | minifyEnabled false
26 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
27 | }
28 | }
29 | compileOptions {
30 | sourceCompatibility JavaVersion.VERSION_1_8
31 | targetCompatibility JavaVersion.VERSION_1_8
32 | }
33 | kotlinOptions {
34 | jvmTarget = '1.8'
35 | }
36 | buildFeatures {
37 | compose true
38 | }
39 | composeOptions {
40 | kotlinCompilerExtensionVersion '1.5.1'
41 | }
42 | packaging {
43 | resources {
44 | excludes += '/META-INF/{AL2.0,LGPL2.1}'
45 | }
46 | }
47 | }
48 |
49 | dependencies {
50 |
51 | implementation libs.androidx.core.ktx
52 | implementation libs.androidx.lifecycle.runtime.ktx
53 | implementation libs.androidx.activity.compose
54 | implementation platform(libs.androidx.compose.bom)
55 | implementation libs.androidx.ui
56 | implementation libs.androidx.ui.graphics
57 | implementation libs.androidx.ui.tooling.preview
58 | implementation libs.androidx.material3
59 | implementation libs.androidx.appcompat
60 | implementation libs.material
61 | implementation libs.androidx.activity
62 | implementation libs.androidx.constraintlayout
63 | testImplementation libs.junit
64 | androidTestImplementation libs.androidx.junit
65 | androidTestImplementation libs.androidx.espresso.core
66 | androidTestImplementation platform(libs.androidx.compose.bom)
67 | androidTestImplementation libs.androidx.ui.test.junit4
68 | debugImplementation libs.androidx.ui.tooling
69 | debugImplementation libs.androidx.ui.test.manifest
70 | }
--------------------------------------------------------------------------------
/gradle/libs.versions.toml:
--------------------------------------------------------------------------------
1 | [versions]
2 | agp = "8.5.0"
3 | kotlin = "1.9.0"
4 | coreKtx = "1.10.1"
5 | junit = "4.13.2"
6 | junitVersion = "1.1.5"
7 | espressoCore = "3.5.1"
8 | lifecycleRuntimeKtx = "2.6.1"
9 | activityCompose = "1.8.0"
10 | composeBom = "2024.04.01"
11 | appcompat = "1.6.1"
12 | material = "1.10.0"
13 | activity = "1.8.0"
14 | constraintlayout = "2.1.4"
15 |
16 | [libraries]
17 | androidx-core-ktx = { group = "androidx.core", name = "core-ktx", version.ref = "coreKtx" }
18 | junit = { group = "junit", name = "junit", version.ref = "junit" }
19 | androidx-junit = { group = "androidx.test.ext", name = "junit", version.ref = "junitVersion" }
20 | androidx-espresso-core = { group = "androidx.test.espresso", name = "espresso-core", version.ref = "espressoCore" }
21 | androidx-lifecycle-runtime-ktx = { group = "androidx.lifecycle", name = "lifecycle-runtime-ktx", version.ref = "lifecycleRuntimeKtx" }
22 | androidx-activity-compose = { group = "androidx.activity", name = "activity-compose", version.ref = "activityCompose" }
23 | androidx-compose-bom = { group = "androidx.compose", name = "compose-bom", version.ref = "composeBom" }
24 | androidx-ui = { group = "androidx.compose.ui", name = "ui" }
25 | androidx-ui-graphics = { group = "androidx.compose.ui", name = "ui-graphics" }
26 | androidx-ui-tooling = { group = "androidx.compose.ui", name = "ui-tooling" }
27 | androidx-ui-tooling-preview = { group = "androidx.compose.ui", name = "ui-tooling-preview" }
28 | androidx-ui-test-manifest = { group = "androidx.compose.ui", name = "ui-test-manifest" }
29 | androidx-ui-test-junit4 = { group = "androidx.compose.ui", name = "ui-test-junit4" }
30 | androidx-material3 = { group = "androidx.compose.material3", name = "material3" }
31 | androidx-appcompat = { group = "androidx.appcompat", name = "appcompat", version.ref = "appcompat" }
32 | material = { group = "com.google.android.material", name = "material", version.ref = "material" }
33 | androidx-activity = { group = "androidx.activity", name = "activity", version.ref = "activity" }
34 | androidx-constraintlayout = { group = "androidx.constraintlayout", name = "constraintlayout", version.ref = "constraintlayout" }
35 |
36 | [plugins]
37 | android-application = { id = "com.android.application", version.ref = "agp" }
38 | jetbrains-kotlin-android = { id = "org.jetbrains.kotlin.android", version.ref = "kotlin" }
39 |
40 |
--------------------------------------------------------------------------------
/.idea/inspectionProfiles/Project_Default.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @rem
2 | @rem Copyright 2015 the original author or authors.
3 | @rem
4 | @rem Licensed under the Apache License, Version 2.0 (the "License");
5 | @rem you may not use this file except in compliance with the License.
6 | @rem You may obtain a copy of the License at
7 | @rem
8 | @rem https://www.apache.org/licenses/LICENSE-2.0
9 | @rem
10 | @rem Unless required by applicable law or agreed to in writing, software
11 | @rem distributed under the License is distributed on an "AS IS" BASIS,
12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | @rem See the License for the specific language governing permissions and
14 | @rem limitations under the License.
15 | @rem
16 |
17 | @if "%DEBUG%" == "" @echo off
18 | @rem ##########################################################################
19 | @rem
20 | @rem Gradle startup script for Windows
21 | @rem
22 | @rem ##########################################################################
23 |
24 | @rem Set local scope for the variables with windows NT shell
25 | if "%OS%"=="Windows_NT" setlocal
26 |
27 | set DIRNAME=%~dp0
28 | if "%DIRNAME%" == "" set DIRNAME=.
29 | set APP_BASE_NAME=%~n0
30 | set APP_HOME=%DIRNAME%
31 |
32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter.
33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
34 |
35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
37 |
38 | @rem Find java.exe
39 | if defined JAVA_HOME goto findJavaFromJavaHome
40 |
41 | set JAVA_EXE=java.exe
42 | %JAVA_EXE% -version >NUL 2>&1
43 | if "%ERRORLEVEL%" == "0" goto execute
44 |
45 | echo.
46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
47 | echo.
48 | echo Please set the JAVA_HOME variable in your environment to match the
49 | echo location of your Java installation.
50 |
51 | goto fail
52 |
53 | :findJavaFromJavaHome
54 | set JAVA_HOME=%JAVA_HOME:"=%
55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
56 |
57 | if exist "%JAVA_EXE%" goto execute
58 |
59 | echo.
60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
61 | echo.
62 | echo Please set the JAVA_HOME variable in your environment to match the
63 | echo location of your Java installation.
64 |
65 | goto fail
66 |
67 | :execute
68 | @rem Setup the command line
69 |
70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
71 |
72 |
73 | @rem Execute Gradle
74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
75 |
76 | :end
77 | @rem End local scope for the variables with windows NT shell
78 | if "%ERRORLEVEL%"=="0" goto mainEnd
79 |
80 | :fail
81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
82 | rem the _cmd.exe /c_ return code!
83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
84 | exit /b 1
85 |
86 | :mainEnd
87 | if "%OS%"=="Windows_NT" endlocal
88 |
89 | :omega
90 |
--------------------------------------------------------------------------------
/.idea/codeStyles:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 | xmlns:android
13 |
14 | ^$
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 | xmlns:.*
24 |
25 | ^$
26 |
27 |
28 | BY_NAME
29 |
30 |
31 |
32 |
33 |
34 |
35 | .*:id
36 |
37 | http://schemas.android.com/apk/res/android
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 | .*:name
47 |
48 | http://schemas.android.com/apk/res/android
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 | name
58 |
59 | ^$
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 | style
69 |
70 | ^$
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 | .*
80 |
81 | ^$
82 |
83 |
84 | BY_NAME
85 |
86 |
87 |
88 |
89 |
90 |
91 | .*
92 |
93 | http://schemas.android.com/apk/res/android
94 |
95 |
96 | ANDROID_ATTRIBUTE_ORDER
97 |
98 |
99 |
100 |
101 |
102 |
103 | .*
104 |
105 | .*
106 |
107 |
108 | BY_NAME
109 |
110 |
111 |
112 |
113 |
114 |
115 |
116 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_launcher_background.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
10 |
15 |
20 |
25 |
30 |
35 |
40 |
45 |
50 |
55 |
60 |
65 |
70 |
75 |
80 |
85 |
90 |
95 |
100 |
105 |
110 |
115 |
120 |
125 |
130 |
135 |
140 |
145 |
150 |
155 |
160 |
165 |
170 |
171 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | #
4 | # Copyright 2015 the original author or authors.
5 | #
6 | # Licensed under the Apache License, Version 2.0 (the "License");
7 | # you may not use this file except in compliance with the License.
8 | # You may obtain a copy of the License at
9 | #
10 | # https://www.apache.org/licenses/LICENSE-2.0
11 | #
12 | # Unless required by applicable law or agreed to in writing, software
13 | # distributed under the License is distributed on an "AS IS" BASIS,
14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | # See the License for the specific language governing permissions and
16 | # limitations under the License.
17 | #
18 |
19 | ##############################################################################
20 | ##
21 | ## Gradle start up script for UN*X
22 | ##
23 | ##############################################################################
24 |
25 | # Attempt to set APP_HOME
26 | # Resolve links: $0 may be a link
27 | PRG="$0"
28 | # Need this for relative symlinks.
29 | while [ -h "$PRG" ] ; do
30 | ls=`ls -ld "$PRG"`
31 | link=`expr "$ls" : '.*-> \(.*\)$'`
32 | if expr "$link" : '/.*' > /dev/null; then
33 | PRG="$link"
34 | else
35 | PRG=`dirname "$PRG"`"/$link"
36 | fi
37 | done
38 | SAVED="`pwd`"
39 | cd "`dirname \"$PRG\"`/" >/dev/null
40 | APP_HOME="`pwd -P`"
41 | cd "$SAVED" >/dev/null
42 |
43 | APP_NAME="Gradle"
44 | APP_BASE_NAME=`basename "$0"`
45 |
46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
48 |
49 | # Use the maximum available, or set MAX_FD != -1 to use that value.
50 | MAX_FD="maximum"
51 |
52 | warn () {
53 | echo "$*"
54 | }
55 |
56 | die () {
57 | echo
58 | echo "$*"
59 | echo
60 | exit 1
61 | }
62 |
63 | # OS specific support (must be 'true' or 'false').
64 | cygwin=false
65 | msys=false
66 | darwin=false
67 | nonstop=false
68 | case "`uname`" in
69 | CYGWIN* )
70 | cygwin=true
71 | ;;
72 | Darwin* )
73 | darwin=true
74 | ;;
75 | MINGW* )
76 | msys=true
77 | ;;
78 | NONSTOP* )
79 | nonstop=true
80 | ;;
81 | esac
82 |
83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
84 |
85 |
86 | # Determine the Java command to use to start the JVM.
87 | if [ -n "$JAVA_HOME" ] ; then
88 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
89 | # IBM's JDK on AIX uses strange locations for the executables
90 | JAVACMD="$JAVA_HOME/jre/sh/java"
91 | else
92 | JAVACMD="$JAVA_HOME/bin/java"
93 | fi
94 | if [ ! -x "$JAVACMD" ] ; then
95 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
96 |
97 | Please set the JAVA_HOME variable in your environment to match the
98 | location of your Java installation."
99 | fi
100 | else
101 | JAVACMD="java"
102 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
103 |
104 | Please set the JAVA_HOME variable in your environment to match the
105 | location of your Java installation."
106 | fi
107 |
108 | # Increase the maximum file descriptors if we can.
109 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
110 | MAX_FD_LIMIT=`ulimit -H -n`
111 | if [ $? -eq 0 ] ; then
112 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
113 | MAX_FD="$MAX_FD_LIMIT"
114 | fi
115 | ulimit -n $MAX_FD
116 | if [ $? -ne 0 ] ; then
117 | warn "Could not set maximum file descriptor limit: $MAX_FD"
118 | fi
119 | else
120 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
121 | fi
122 | fi
123 |
124 | # For Darwin, add options to specify how the application appears in the dock
125 | if $darwin; then
126 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
127 | fi
128 |
129 | # For Cygwin or MSYS, switch paths to Windows format before running java
130 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
131 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
132 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
133 |
134 | JAVACMD=`cygpath --unix "$JAVACMD"`
135 |
136 | # We build the pattern for arguments to be converted via cygpath
137 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
138 | SEP=""
139 | for dir in $ROOTDIRSRAW ; do
140 | ROOTDIRS="$ROOTDIRS$SEP$dir"
141 | SEP="|"
142 | done
143 | OURCYGPATTERN="(^($ROOTDIRS))"
144 | # Add a user-defined pattern to the cygpath arguments
145 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
146 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
147 | fi
148 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
149 | i=0
150 | for arg in "$@" ; do
151 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
152 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
153 |
154 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
155 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
156 | else
157 | eval `echo args$i`="\"$arg\""
158 | fi
159 | i=`expr $i + 1`
160 | done
161 | case $i in
162 | 0) set -- ;;
163 | 1) set -- "$args0" ;;
164 | 2) set -- "$args0" "$args1" ;;
165 | 3) set -- "$args0" "$args1" "$args2" ;;
166 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;;
167 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
168 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
169 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
170 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
171 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
172 | esac
173 | fi
174 |
175 | # Escape application args
176 | save () {
177 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
178 | echo " "
179 | }
180 | APP_ARGS=`save "$@"`
181 |
182 | # Collect all arguments for the java command, following the shell quoting and substitution rules
183 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
184 |
185 | exec "$JAVACMD" "$@"
186 |
--------------------------------------------------------------------------------
/app/src/main/java/portrait/bala/portrait/MainActivity.java:
--------------------------------------------------------------------------------
1 | package portrait.bala.portrait;
2 |
3 | import android.Manifest;
4 | import android.app.Activity;
5 | import android.content.ContentValues;
6 | import android.content.Intent;
7 | import android.content.pm.PackageManager;
8 | import android.database.Cursor;
9 | import android.graphics.Bitmap;
10 | import android.graphics.BitmapFactory;
11 | import android.net.Uri;
12 | import android.os.Build;
13 | import android.os.Bundle;
14 | import android.os.Environment;
15 | import android.provider.MediaStore;
16 | import android.util.Log;
17 | import android.view.View;
18 | import android.widget.Button;
19 | import android.widget.ImageView;
20 |
21 | import java.io.File;
22 |
23 | import androidx.activity.ComponentActivity;
24 | import androidx.activity.result.ActivityResultLauncher;
25 | import androidx.activity.result.contract.ActivityResultContracts;
26 | import androidx.annotation.NonNull;
27 | import androidx.core.app.ActivityCompat;
28 | import androidx.core.content.FileProvider;
29 |
30 | import static android.os.Environment.DIRECTORY_PICTURES;
31 |
32 | public class MainActivity extends ComponentActivity {
33 |
34 | //改变头像的标记位
35 | private ImageView headImage = null;
36 |
37 | private final int PERMISSION_CAMERA = 0;//读和相机权限
38 | private final int PERMISSION_READ = 1;//读取权限
39 |
40 | private final String picPermission = PermissionUtil.getReadImgPermission();
41 | private Uri fileUri;
42 | private boolean isToCrop = true;
43 |
44 | private ActivityResultLauncher cropLauncher;
45 | private ActivityResultLauncher takePhotoLauncher;
46 | private ActivityResultLauncher albumLauncher;
47 |
48 |
49 | @Override
50 | protected void onCreate(Bundle savedInstanceState) {
51 | super.onCreate(savedInstanceState);
52 | setContentView(R.layout.activity_main);
53 | headImage = (ImageView) findViewById(R.id.imageView);
54 | Button buttonLocal = (Button) findViewById(R.id.buttonLocal);
55 | buttonLocal.setOnClickListener(new View.OnClickListener() {
56 |
57 | @Override
58 | public void onClick(View v) {
59 | checkPicPermission();
60 | }
61 | });
62 |
63 | Button buttonCamera = (Button) findViewById(R.id.buttonCamera);
64 | buttonCamera.setOnClickListener(new View.OnClickListener() {
65 |
66 | @Override
67 | public void onClick(View v) {
68 | checkCameraPermission();//检查是否有权限
69 | }
70 | });
71 | cropLauncher =
72 | registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
73 | if (result.getResultCode() != Activity.RESULT_OK) return;
74 | setImageToHeadView(result.getData().getData());
75 | });
76 | albumLauncher =
77 | registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
78 | Log.d("eeeeee", "getData===" + result.getData().getData());
79 | if (result.getResultCode() != Activity.RESULT_OK) return;
80 | try {
81 | if (isToCrop) {
82 | cropRawPhoto(result.getData().getData());
83 | } else {
84 | setImageToHeadView(result.getData().getData());
85 | }
86 | } catch (Exception e) {
87 | Log.d("eeeeee", "albumLauncher====Exception");
88 | e.printStackTrace();
89 | }
90 |
91 | });
92 | takePhotoLauncher =
93 | registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
94 | if (result.getResultCode() != Activity.RESULT_OK) return;
95 | try {
96 | if (isToCrop) {
97 | cropRawPhoto(fileUri);
98 | } else {
99 | setImageToHeadView(fileUri);
100 | }
101 | } catch (Exception e) {
102 | e.printStackTrace();
103 | }
104 | });
105 | }
106 |
107 | // 从本地相册选取图片作为头像
108 | private void choseHeadImageFromGallery() {
109 | Intent intentFromGallery = new Intent(Intent.ACTION_PICK, null);
110 | intentFromGallery.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
111 | // startActivityForResult(intentFromGallery, CODE_GALLERY_REQUEST);
112 | albumLauncher.launch(intentFromGallery);
113 | }
114 |
115 | // 启动手机相机拍摄照片作为头像
116 | private void choseHeadImageFromCameraCapture() {
117 | File file = buildTemporaryFile();
118 | Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
119 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { //如果是7.0以上,使用FileProvider,否则会报错
120 | intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
121 | fileUri = FileProvider.getUriForFile(this,
122 | getPackageName() + ".fileProvider", file);
123 | intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); //设置拍照后图片保存的位置
124 | }
125 | intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString()); //设置图片保存的格式
126 | takePhotoLauncher.launch(intent);
127 | }
128 |
129 | private void checkCameraPermission() {
130 | int result = ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
131 | if (result == PackageManager.PERMISSION_DENIED) {
132 | String[] permissions = {Manifest.permission.CAMERA};
133 | ActivityCompat.requestPermissions(this, permissions, PERMISSION_CAMERA);
134 | } else {
135 | choseHeadImageFromCameraCapture();
136 | }
137 | }
138 |
139 | private void checkPicPermission() {
140 | int permission = ActivityCompat.checkSelfPermission(this, picPermission);
141 | if (permission == PackageManager.PERMISSION_DENIED) {
142 | String[] permissions = {picPermission};
143 | ActivityCompat.requestPermissions(this, permissions, PERMISSION_READ);
144 | } else {
145 | choseHeadImageFromGallery();
146 | }
147 | }
148 |
149 | //权限申请回调
150 | @Override
151 | public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
152 | super.onRequestPermissionsResult(requestCode, permissions, grantResults);
153 |
154 | switch (requestCode) {
155 | case PERMISSION_CAMERA:
156 | if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
157 | choseHeadImageFromCameraCapture();
158 | }
159 | break;
160 | case PERMISSION_READ:
161 | if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
162 | choseHeadImageFromGallery();
163 | }
164 | break;
165 | }
166 |
167 | }
168 |
169 | /**
170 | * 裁剪原始的图片
171 | */
172 | public void cropRawPhoto(Uri uri) {
173 | Intent intent = new Intent("com.android.camera.action.CROP");
174 | intent.putExtra("crop", "true");
175 | intent.putExtra("aspectX", 1); //X方向上的比例
176 | intent.putExtra("aspectY", 1); //Y方向上的比例
177 | intent.putExtra("outputX", 500); //裁剪区的宽
178 | intent.putExtra("outputY", 500);//裁剪区的高
179 | intent.putExtra("scale ", true); //是否保留比例
180 | intent.putExtra("return-data", false);
181 | intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
182 | intent.setDataAndType(uri, "image/*");
183 |
184 | // 7.0 使用 FileProvider 并赋予临时权限
185 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
186 | intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION/* | Intent.FLAG_GRANT_WRITE_URI_PERMISSION*/);
187 | }
188 | File temporaryFile = buildTemporaryFile();
189 | if (Build.VERSION.SDK_INT == Build.VERSION_CODES.R || Build.VERSION.SDK_INT > Build.VERSION_CODES.S) { //R = Android 11 S = Android 12
190 | createCropImageFile();
191 | intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
192 | } else {
193 | intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri = Uri.fromFile(temporaryFile)); //设置输出
194 | }
195 | cropLauncher.launch(intent);
196 | }
197 |
198 | public File buildTemporaryFile() {
199 | File file;
200 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { //Android 10
201 | file = new File(Environment.getExternalStoragePublicDirectory(DIRECTORY_PICTURES),
202 | System.currentTimeMillis() + ".jpg");
203 | } else {
204 | file = new File(getExternalCacheDir(), System.currentTimeMillis() + ".jpg");
205 | }
206 | return file;
207 | }
208 |
209 | public void createCropImageFile() {
210 | try {
211 | long currentTimeMillis = System.currentTimeMillis();
212 | String fileName = "IMG_" + currentTimeMillis + "_CROP.jpg";
213 | File imgFile = new File(Environment.getExternalStoragePublicDirectory(DIRECTORY_PICTURES) + File.separator + fileName);
214 | String absolutePath = imgFile.getAbsolutePath();
215 | Cursor cursor = getContentResolver().query(
216 | MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
217 | new String[]{MediaStore.Images.Media._ID},
218 | MediaStore.Images.Media.DATA + "=? ",
219 | new String[]{absolutePath}, null);
220 | if (cursor != null && cursor.moveToFirst()) {
221 | int cursorColumnIndex = cursor.getColumnIndex(MediaStore.MediaColumns._ID);
222 | if (cursorColumnIndex >= 0) {
223 | int id = cursor.getInt(cursorColumnIndex);
224 | Uri baseUri = Uri.parse("content://media/external/images/media");
225 | fileUri = Uri.withAppendedPath(baseUri, "" + id);
226 | return;
227 | }
228 | }
229 | // 通过 MediaStore API 插入file 为了拿到系统裁剪要保存到的uri(因为App没有权限不能访问公共存储空间,需要通过 MediaStore API来操作)
230 | ContentValues values = new ContentValues();
231 | values.put(MediaStore.Images.Media.DATA, absolutePath);
232 | values.put(MediaStore.Images.Media.DISPLAY_NAME, fileName);
233 | values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
234 | fileUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
235 | } catch (Exception e) {
236 | e.printStackTrace();
237 | }
238 | }
239 |
240 | /**
241 | * 提取保存裁剪之后的图片数据,并设置头像部分的View
242 | */
243 | private void setImageToHeadView(Uri uri) {
244 | try {
245 | Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri));
246 | headImage.setImageBitmap(bitmap);
247 | } catch (Exception e) {
248 | e.printStackTrace();
249 | }
250 | }
251 | }
252 |
--------------------------------------------------------------------------------
/app/src/main/java/portrait/bala/portrait/FileUtil.java:
--------------------------------------------------------------------------------
1 | package portrait.bala.portrait;
2 |
3 | import android.annotation.SuppressLint;
4 | import android.content.ContentResolver;
5 | import android.content.ContentUris;
6 | import android.content.Context;
7 | import android.database.Cursor;
8 | import android.graphics.Bitmap;
9 | import android.net.Uri;
10 | import android.os.Build;
11 | import android.os.Environment;
12 | import android.os.FileUtils;
13 | import android.provider.DocumentsContract;
14 | import android.provider.MediaStore;
15 | import android.provider.OpenableColumns;
16 | import android.text.TextUtils;
17 |
18 | import java.io.BufferedInputStream;
19 | import java.io.BufferedOutputStream;
20 | import java.io.ByteArrayOutputStream;
21 | import java.io.File;
22 | import java.io.FileOutputStream;
23 | import java.io.IOException;
24 | import java.io.InputStream;
25 | import java.io.OutputStream;
26 |
27 | import androidx.annotation.RequiresApi;
28 |
29 | /**
30 | * Created by Administrator on 2017/7/12 0012.
31 | */
32 |
33 | public class FileUtil {
34 |
35 | /**
36 | * 根据Uri获取文件绝对路径,解决Android4.4以上版本Uri转换 兼容Android 10
37 | *
38 | * @param context
39 | * @param imageUri
40 | */
41 | public static String getFileAbsolutePath(Context context, Uri imageUri) {
42 | if (context == null || imageUri == null) {
43 | return null;
44 | }
45 |
46 | //4.4以下的版本
47 | if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.KITKAT) {
48 | return getRealFilePath(context, imageUri);
49 | }
50 |
51 | //大于4.4,小于10
52 | if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT && android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.Q && DocumentsContract.isDocumentUri(context, imageUri)) {
53 |
54 | if (isExternalStorageDocument(imageUri)) {
55 | String docId = DocumentsContract.getDocumentId(imageUri);
56 | String[] split = docId.split(":");
57 | String type = split[0];
58 | if ("primary".equalsIgnoreCase(type)) {
59 | return Environment.getExternalStorageDirectory() + "/" + split[1];
60 | }
61 | } else if (isDownloadsDocument(imageUri)) {
62 | String id = DocumentsContract.getDocumentId(imageUri);
63 | Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads" +
64 | "/public_downloads"), Long.valueOf(id));
65 | return getDataColumn(context, contentUri, null, null);
66 | } else if (isMediaDocument(imageUri)) {
67 | String docId = DocumentsContract.getDocumentId(imageUri);
68 | String[] split = docId.split(":");
69 | String type = split[0];
70 | Uri contentUri = null;
71 | if ("image".equals(type)) {
72 | contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
73 | } else if ("video".equals(type)) {
74 | contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
75 | } else if ("audio".equals(type)) {
76 | contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
77 | }
78 | String selection = MediaStore.Images.Media._ID + "=?";
79 | String[] selectionArgs = new String[]{split[1]};
80 | return getDataColumn(context, contentUri, selection, selectionArgs);
81 | }
82 | }
83 |
84 | // MediaStore (and general) 大于等于10
85 | if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
86 | return uriToFileApiQ(context, imageUri);
87 | } else if ("content".equalsIgnoreCase(imageUri.getScheme())) {
88 | // Return the remote address
89 | if (isGooglePhotosUri(imageUri)) {
90 | return imageUri.getLastPathSegment();
91 | }
92 | if (Build.VERSION.SDK_INT >= 24) {
93 | return getFilePathFromUri(context, imageUri); //content 类型
94 | } else {
95 | return getDataColumn(context, imageUri, null, null);
96 | }
97 | }
98 | // File
99 | else if ("file".equalsIgnoreCase(imageUri.getScheme())) {
100 | return imageUri.getPath();
101 | }
102 | return null;
103 | }
104 |
105 | private static String getDataColumn(Context context, Uri uri, String selection,
106 | String[] selectionArgs) {
107 | Cursor cursor = null;
108 | String column = MediaStore.Images.Media.DATA;
109 | String[] projection = {column};
110 | try {
111 | cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs
112 | , null);
113 | if (cursor != null && cursor.moveToFirst()) {
114 | int index = cursor.getColumnIndexOrThrow(column);
115 | return cursor.getString(index);
116 | }
117 | }catch (Exception E){
118 | E.printStackTrace();
119 | }
120 | finally {
121 | if (cursor != null) {
122 | cursor.close();
123 | }
124 | }
125 | return null;
126 | }
127 |
128 | private static String getRealFilePath(final Context context, final Uri uri) {
129 | if (null == uri) {
130 | return null;
131 | }
132 | final String scheme = uri.getScheme();
133 | String data = null;
134 | if (scheme == null) {
135 | data = uri.getPath();
136 | } else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
137 | data = uri.getPath();
138 | } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
139 | String[] projection = {MediaStore.Images.ImageColumns.DATA};
140 | Cursor cursor = context.getContentResolver().query(uri, projection, null, null, null);
141 | if (null != cursor) {
142 | if (cursor.moveToFirst()) {
143 | int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
144 | if (index > -1) {
145 | data = cursor.getString(index);
146 | }
147 | }
148 | cursor.close();
149 | }
150 | }
151 | return data;
152 | }
153 |
154 | private static String getFilePathFromUri(Context context, Uri uri) {
155 | String realFilePath = getRealFilePath(context, uri); //防止获取不到真实的地址,因此这里需要进行判断
156 | if (!TextUtils.isEmpty(realFilePath)) {
157 | return realFilePath;
158 | }
159 | File filesDir = context.getApplicationContext().getFilesDir();
160 | String fileName = getFileName(uri);
161 | if (!TextUtils.isEmpty(fileName)) {
162 | File copyFile1 = new File(filesDir + File.separator + fileName);
163 | copyFile(context, uri, copyFile1);
164 | return copyFile1.getAbsolutePath();
165 | }
166 | return null;
167 | }
168 |
169 | private static void copyFile(Context context, Uri srcUri, File dstFile) {
170 | try {
171 | InputStream inputStream = context.getContentResolver().openInputStream(srcUri);
172 | if (inputStream == null) {
173 | return;
174 | }
175 | OutputStream outputStream = new FileOutputStream(dstFile);
176 | copyStream(inputStream, outputStream);
177 | inputStream.close();
178 | outputStream.close();
179 | } catch (Exception e) {
180 | e.printStackTrace();
181 | }
182 | }
183 |
184 | private static int copyStream(InputStream input, OutputStream output) {
185 | final int BUFFER_SIZE = 1024 * 2;
186 | byte[] buffer = new byte[BUFFER_SIZE];
187 | BufferedInputStream in = new BufferedInputStream(input, BUFFER_SIZE);
188 | BufferedOutputStream out = new BufferedOutputStream(output, BUFFER_SIZE);
189 | int count = 0, n = 0;
190 | try {
191 | while ((n = in.read(buffer, 0, BUFFER_SIZE)) != -1) {
192 | out.write(buffer, 0, n);
193 | count += n;
194 | }
195 | out.flush();
196 | } catch (Exception e) {
197 | } finally {
198 | try {
199 | out.close();
200 | in.close();
201 | } catch (Exception e) {
202 | }
203 | }
204 | return count;
205 | }
206 |
207 | private static String getFileName(Uri uri) {
208 | if (uri == null) {
209 | return null;
210 | }
211 | String fileName = null;
212 | String path = uri.getPath();
213 | int cut = path.lastIndexOf('/');
214 | if (cut != -1) {
215 | fileName = path.substring(cut + 1);
216 | }
217 | return fileName;
218 | }
219 |
220 | /**
221 | * @param uri The Uri to check.
222 | * @return Whether the Uri authority is MediaProvider.
223 | */
224 | private static boolean isMediaDocument(Uri uri) {
225 | return "com.android.providers.media.documents".equals(uri.getAuthority());
226 | }
227 |
228 | /**
229 | * @param uri The Uri to check.
230 | * @return Whether the Uri authority is ExternalStorageProvider.
231 | */
232 | private static boolean isExternalStorageDocument(Uri uri) {
233 | return "com.android.externalstorage.documents".equals(uri.getAuthority());
234 | }
235 |
236 | /**
237 | * @param uri The Uri to check.
238 | * @return Whether the Uri authority is DownloadsProvider.
239 | */
240 | private static boolean isDownloadsDocument(Uri uri) {
241 | return "com.android.providers.downloads.documents".equals(uri.getAuthority());
242 | }
243 |
244 | /**
245 | * @param uri The Uri to check.
246 | * @return Whether the Uri authority is Google Photos.
247 | */
248 | private static boolean isGooglePhotosUri(Uri uri) {
249 | return "com.google.android.apps.photos.content".equals(uri.getAuthority());
250 | }
251 |
252 | /**
253 | * Android 10 以上适配
254 | *
255 | * @param context
256 | * @param uri
257 | * @return
258 | */
259 | @RequiresApi(api = Build.VERSION_CODES.Q)
260 | private static String uriToFileApiQ(Context context, Uri uri) {
261 | File file = null;
262 | //android10以上转换
263 | if (uri.getScheme().equals(ContentResolver.SCHEME_FILE)) {
264 | file = new File(uri.getPath());
265 | } else if (uri.getScheme().equals(ContentResolver.SCHEME_CONTENT)) {
266 | //把文件复制到沙盒目录
267 | ContentResolver contentResolver = context.getContentResolver();
268 | Cursor cursor = contentResolver.query(uri, null, null, null, null);
269 | if (cursor.moveToFirst()) {
270 | @SuppressLint("Range") String displayName =
271 | cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
272 | try {
273 | InputStream is = contentResolver.openInputStream(uri);
274 | File file1 =
275 | new File(context.getExternalCacheDir().getAbsolutePath() + "/" + System.currentTimeMillis());
276 | if (!file1.exists()) {
277 | file1.mkdir();
278 | }
279 | File cache = new File(file1.getPath(), displayName);
280 | FileOutputStream fos = new FileOutputStream(cache);
281 | FileUtils.copy(is, fos);
282 | file = cache;
283 | fos.close();
284 | is.close();
285 | } catch (IOException e) {
286 | e.printStackTrace();
287 | }
288 | }
289 | }
290 | return file.getAbsolutePath();
291 | }
292 |
293 | /**
294 | * 获取目录文件大小
295 | *
296 | * @param dir
297 | * @return
298 | */
299 | public static long getDirSize(File dir) {
300 | if (dir == null) {
301 | return 0;
302 | }
303 | if (!dir.isDirectory()) {
304 | return 0;
305 | }
306 | long dirSize = 0;
307 | File[] files = dir.listFiles();
308 | for (File file : files) {
309 | if (file.isFile()) {
310 | dirSize += file.length();
311 | } else if (file.isDirectory()) {
312 | dirSize += file.length();
313 | dirSize += getDirSize(file); // 递归调用继续统计
314 | }
315 | }
316 | return dirSize;
317 | }
318 |
319 | /**
320 | * 转换文件大小
321 | *
322 | * @param fileS
323 | * @return B/KB/MB/GB
324 | */
325 | public static String formatFileSize(long fileS) {
326 | java.text.DecimalFormat df = new java.text.DecimalFormat("#.00");
327 | String fileSizeString = "";
328 | if (fileS < 1024) {
329 | fileSizeString = df.format((double) fileS) + "B";
330 | } else if (fileS < 1048576) {
331 | fileSizeString = df.format((double) fileS / 1024) + "KB";
332 | } else if (fileS < 1073741824) {
333 | fileSizeString = df.format((double) fileS / 1048576) + "MB";
334 | } else {
335 | fileSizeString = df.format((double) fileS / 1073741824) + "G";
336 | }
337 | return fileSizeString;
338 | }
339 |
340 | public static File saveFile(String filePath,String fileName, Bitmap bitmap){
341 | ByteArrayOutputStream baos =new ByteArrayOutputStream();
342 | bitmap.compress(Bitmap.CompressFormat.JPEG,100,baos);
343 | byte[] bytes = baos.toByteArray();
344 | try {
345 | File file = new File(filePath, fileName);
346 | FileOutputStream fos = new FileOutputStream(file);
347 | fos.write(bytes);
348 | fos.close();
349 | return file;
350 | } catch (Exception e) {
351 | e.printStackTrace();
352 | return null;
353 | }
354 |
355 | }
356 | }
357 |
--------------------------------------------------------------------------------