sizes, int w, int h) {
final double ASPECT_TOLERANCE = 0.1;
double targetRatio = (double) h / w;
if (sizes == null) return null;
Camera.Size optimalSize = null;
double minDiff = Double.MAX_VALUE;
for (Camera.Size size : sizes) {
double ratio = (double) size.width / size.height;
if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE) continue;
if (Math.abs(size.height - h) < minDiff) {
optimalSize = size;
minDiff = Math.abs(size.height - h);
}
}
if (optimalSize == null) {
minDiff = Double.MAX_VALUE;
for (Camera.Size size : sizes) {
if (Math.abs(size.height - h) < minDiff) {
optimalSize = size;
minDiff = Math.abs(size.height - h);
}
}
}
return optimalSize;
}
@Override
public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
camera.stopPreview();
camera.release();
return true;
}
@Override
public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {
}
@Override
public void onSurfaceTextureUpdated(SurfaceTexture surface) {
}
}
================================================
FILE: demo/src/main/java/io/github/muddz/quickshot/demo/fragments/ViewFragment.java
================================================
package io.github.muddz.quickshot.demo.fragments;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import io.github.muddz.quickshot.demo.DrawingBoardView;
import io.github.muddz.quickshot.demo.R;
/**
* Created by Muddz on 23-08-2017.
*/
public class ViewFragment extends BaseFragment implements DrawingBoardView.OnDrawingListener {
private DrawingBoardView drawingBoardView;
private LinearLayout drawHint;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.view_fragment, container, false);
drawingBoardView = v.findViewById(R.id.drawingview);
drawingBoardView.setOnDrawingListener(this);
drawHint = v.findViewById(R.id.drawhint);
return v;
}
@Override
public View getTargetView() {
return drawingBoardView;
}
@Override
public void onDrawingStarted() {
drawHint.setVisibility(View.GONE);
}
}
================================================
FILE: demo/src/main/res/drawable/ic_launcher_background.xml
================================================
================================================
FILE: demo/src/main/res/drawable/ic_save_black_24dp.xml
================================================
================================================
FILE: demo/src/main/res/drawable/ic_select.xml
================================================
================================================
FILE: demo/src/main/res/drawable-v24/ic_launcher_foreground.xml
================================================
================================================
FILE: demo/src/main/res/layout/activity_main.xml
================================================
================================================
FILE: demo/src/main/res/layout/surface_fragment.xml
================================================
================================================
FILE: demo/src/main/res/layout/texture_fragment.xml
================================================
================================================
FILE: demo/src/main/res/layout/view_fragment.xml
================================================
================================================
FILE: demo/src/main/res/menu/menu_toolbar.xml
================================================
================================================
FILE: demo/src/main/res/mipmap-anydpi-v26/ic_launcher.xml
================================================
================================================
FILE: demo/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml
================================================
================================================
FILE: demo/src/main/res/values/colors.xml
================================================
#3F51B5
#303F9F
#8f8f8f
================================================
FILE: demo/src/main/res/values/strings.xml
================================================
QuickShot demo
================================================
FILE: demo/src/main/res/values/styles.xml
================================================
================================================
FILE: gradle/wrapper/gradle-wrapper.properties
================================================
#Sun Aug 01 22:32:07 CEST 2021
distributionBase=GRADLE_USER_HOME
distributionUrl=https\://services.gradle.org/distributions/gradle-7.0.2-bin.zip
distributionPath=wrapper/dists
zipStorePath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
================================================
FILE: gradle.properties
================================================
android.enableJetifier=true
android.useAndroidX=true
#MavenCentral publish informations
#Publish plugin: https://github.com/vanniktech/gradle-maven-publish-plugin
GROUP=io.github.muddz
POM_ARTIFACT_ID=quickshot
VERSION_NAME=1.4.0
POM_NAME=quickshot
POM_DESCRIPTION=Capture images of any View, SurfaceView or Bitmap from your Android app in: .jpg .png or .nomedia with simple oneliner codes.
POM_INCEPTION_YEAR=2021
POM_URL=https://github.com/Muddz/QuickShot
POM_LICENSE_NAME=The Apache Software License, Version 2.0
POM_LICENSE_URL=https://www.apache.org/licenses/LICENSE-2.0.txt
POM_LICENSE_DIST=repo
POM_SCM_URL=https://github.com/Muddz/Quickshot
POM_SCM_CONNECTION=scm:git:git://github.com/Muddz/Quickshot.git
POM_SCM_DEV_CONNECTION=scm:git:ssh://git@github.com/Muddz/Quickshot.git
POM_DEVELOPER_ID=Muddz
POM_DEVELOPER_NAME=Muddi Walid
================================================
FILE: gradlew
================================================
#!/usr/bin/env sh
#
# Copyright 2015 the original author or authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn () {
echo "$*"
}
die () {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin or MSYS, switch paths to Windows format before running java
if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=`expr $i + 1`
done
case $i in
0) set -- ;;
1) set -- "$args0" ;;
2) set -- "$args0" "$args1" ;;
3) set -- "$args0" "$args1" "$args2" ;;
4) set -- "$args0" "$args1" "$args2" "$args3" ;;
5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Escape application args
save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=`save "$@"`
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
exec "$JAVACMD" "$@"
================================================
FILE: gradlew.bat
================================================
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto execute
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
================================================
FILE: license
================================================
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
Copyright 2018 Muddi Walid.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
================================================
FILE: quickshot/.gitignore
================================================
/build
================================================
FILE: quickshot/build.gradle
================================================
plugins {
id 'com.android.library'
id 'com.vanniktech.maven.publish'
}
android {
compileSdk 30
defaultConfig {
minSdk 19
targetSdk 30
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.3.1'
implementation 'com.google.android.material:material:1.4.0'
androidTestImplementation 'androidx.test:runner:1.4.0'
androidTestImplementation 'androidx.test:rules:1.4.0'
}
================================================
FILE: quickshot/consumer-rules.pro
================================================
================================================
FILE: quickshot/proguard-rules.pro
================================================
# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable
# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile
================================================
FILE: quickshot/src/androidTest/java/io/github/muddz/quickshot/QuickShotTest.java
================================================
package io.github.muddz.quickshot;
import static android.view.View.MeasureSpec.EXACTLY;
import android.content.Context;
import android.graphics.Color;
import android.view.View;
import androidx.test.InstrumentationRegistry;
import androidx.test.runner.AndroidJUnit4;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.io.File;
@RunWith(AndroidJUnit4.class)
public class QuickShotTest {
private Context context;
private View testView;
@Before
public void setup() {
testView = generateTestView();
context = androidx.test.platform.app.InstrumentationRegistry.getInstrumentation().getContext();
}
@Test
public void testCallbackPathNotNull() {
QuickShot.of(testView).setResultListener(new QuickShot.QuickShotListener() {
@Override
public void onQuickShotSuccess(String path) {
Assert.assertNotNull(path);
}
@Override
public void onQuickShotFailed(String path, String errorMsg) {
}
}).save();
sleepThread();
}
@Test
public void testIfSavedInJPG() {
QuickShot.of(testView).setResultListener(new QuickShot.QuickShotListener() {
@Override
public void onQuickShotSuccess(String path) {
Assert.assertTrue(path.contains(".jpg"));
}
@Override
public void onQuickShotFailed(String path, String errorMsg) {
}
}).save();
sleepThread();
}
@Test
public void testIfSavedInPNG() {
QuickShot.of(testView).toPNG().setResultListener(new QuickShot.QuickShotListener() {
@Override
public void onQuickShotSuccess(String path) {
Assert.assertTrue(path.contains(".png"));
}
@Override
public void onQuickShotFailed(String path, String errorMsg) {
}
}).save();
sleepThread();
}
@Test
public void testIfSavedInNomedia() {
QuickShot.of(testView).toNomedia().setResultListener(new QuickShot.QuickShotListener() {
@Override
public void onQuickShotSuccess(String path) {
Assert.assertTrue(path.contains(".nomedia"));
}
@Override
public void onQuickShotFailed(String path, String errorMsg) {
}
}).save();
sleepThread();
}
@Test
public void testIfDirectoryWasCreated() {
QuickShot.of(testView).setPath("QuickShotTestDirectory").setResultListener(new QuickShot.QuickShotListener() {
@Override
public void onQuickShotSuccess(String path) {
if (QuickShotUtils.isAboveAPI29()) {
Assert.assertTrue(path.contains("QuickShotTestDirectory"));
} else {
File file = new File(path);
File directory = new File(file.getParent());
boolean isDirectory = directory.exists() && directory.isDirectory();
Assert.assertTrue(isDirectory);
}
}
@Override
public void onQuickShotFailed(String path, String errorMsg) {
}
}).save();
sleepThread();
}
@Test
public void testIfFileExist() {
QuickShot.of(testView).setPath("QuickShotTestDirectory").setResultListener(new QuickShot.QuickShotListener() {
@Override
public void onQuickShotSuccess(String path) {
if (QuickShotUtils.isAboveAPI29()) {
Assert.assertTrue(path != null && path.length() > 0);
} else {
File file = new File(path);
Assert.assertTrue(file.exists());
}
}
@Override
public void onQuickShotFailed(String path, String errorMsg) {
}
}).save();
sleepThread();
}
private View generateTestView() {
int width = 950;
int height = 950;
int widthMS = View.MeasureSpec.makeMeasureSpec(width, EXACTLY);
int heightMS = View.MeasureSpec.makeMeasureSpec(height, EXACTLY);
View view = new View(InstrumentationRegistry.getTargetContext());
view.measure(widthMS, heightMS);
view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
view.setBackgroundColor(Color.GRAY);
return view;
}
private void sleepThread() {
try {
Thread.sleep(1500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
================================================
FILE: quickshot/src/main/AndroidManifest.xml
================================================
================================================
FILE: quickshot/src/main/java/io/github/muddz/quickshot/PixelCopyHelper.java
================================================
package io.github.muddz.quickshot;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Handler;
import android.os.HandlerThread;
import android.view.PixelCopy;
import android.view.SurfaceView;
import androidx.annotation.NonNull;
class PixelCopyHelper {
static void getSurfaceBitmap(@NonNull SurfaceView surfaceView, @NonNull final PixelCopyListener listener) {
final Bitmap bitmap = Bitmap.createBitmap(surfaceView.getWidth(), surfaceView.getHeight(), Bitmap.Config.ARGB_8888);
final HandlerThread handlerThread = new HandlerThread(PixelCopyHelper.class.getSimpleName());
handlerThread.start();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
PixelCopy.request(surfaceView, bitmap, new PixelCopy.OnPixelCopyFinishedListener() {
@Override
public void onPixelCopyFinished(int copyResult) {
if (copyResult == PixelCopy.SUCCESS) {
listener.onSurfaceBitmapReady(bitmap);
} else {
listener.onSurfaceBitmapError("Couldn't create bitmap of the SurfaceView");
}
handlerThread.quitSafely();
}
}, new Handler(handlerThread.getLooper()));
} else {
listener.onSurfaceBitmapError("Saving an image of a SurfaceView is only supported for API 24 and above");
}
}
interface PixelCopyListener {
void onSurfaceBitmapReady(Bitmap bitmap);
void onSurfaceBitmapError(String errorMsg);
}
}
================================================
FILE: quickshot/src/main/java/io/github/muddz/quickshot/QuickShot.java
================================================
package io.github.muddz.quickshot;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.provider.MediaStore;
import android.util.Log;
import android.view.SurfaceView;
import android.view.TextureView;
import android.view.View;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.lang.ref.WeakReference;
import static android.os.Environment.DIRECTORY_PICTURES;
public class QuickShot {
private static final String EXTENSION_JPG = ".jpg";
private static final String EXTENSION_PNG = ".png";
private static final String EXTENSION_NOMEDIA = ".nomedia";
private static final int JPG_MAX_QUALITY = 100;
private boolean printStackTrace;
private int jpgQuality = JPG_MAX_QUALITY;
private String fileExtension = EXTENSION_JPG;
private String filename = String.valueOf(System.currentTimeMillis());
private String path;
private Bitmap bitmap;
private View view;
private Context context;
private QuickShotListener listener;
private QuickShot(@NonNull View view) {
this.view = view;
this.context = view.getContext();
}
private QuickShot(@NonNull Bitmap bitmap, @NonNull Context context) {
this.bitmap = bitmap;
this.context = context;
}
public static QuickShot of(@NonNull View view) {
return new QuickShot(view);
}
public static QuickShot of(@NonNull Bitmap bitmap, @NonNull Context context) {
return new QuickShot(bitmap, context);
}
/**
* @param filename if not set, filename defaults to a timestamp from {@link System#currentTimeMillis}
*/
public QuickShot setFilename(String filename) {
this.filename = filename;
return this;
}
/**
* NOTE: For devices running Android 10 (+API 29) and above image files will now be saved relative to /Internal storage/Pictures/ due to 'Scoped storage'
* Directories which don't already exist will be automatically created.
*
* @param path if not set, path defaults to /Pictures/ regardless of any API level
*/
public QuickShot setPath(String path) {
this.path = path;
return this;
}
private void setFileExtension(String fileExtension) {
this.fileExtension = fileExtension;
}
/**
* Save as .jpg format in highest quality
* default is .jpg
*/
public QuickShot toJPG() {
jpgQuality = JPG_MAX_QUALITY;
setFileExtension(EXTENSION_JPG);
return this;
}
/**
* Save as .jpg format in a custom quality between 0-100
* default is 100
*/
public QuickShot toJPG(int jpgQuality) {
this.jpgQuality = jpgQuality;
setFileExtension(EXTENSION_JPG);
return this;
}
/**
* Save as .png format for lossless compression
* default is .jpg
*/
public QuickShot toPNG() {
setFileExtension(EXTENSION_PNG);
return this;
}
/**
* Save as .nomedia for making the picture invisible for photo viewer apps and galleries.
*/
public QuickShot toNomedia() {
setFileExtension(EXTENSION_NOMEDIA);
return this;
}
/**
* Enable QuickShot to log and print exception stacks
*/
public QuickShot enableLogging() {
printStackTrace = true;
return this;
}
/**
* Listen for successive or failure results when calling save()
*/
public QuickShot setResultListener(@NonNull QuickShotListener listener) {
this.listener = listener;
if (listener == null) {
throw new NullPointerException("QuickShot.setResultListener() was provided with a null object reference");
}
return this;
}
private Context getContext() {
if (context == null) {
throw new NullPointerException("Attempt to save the picture failed: View or Context was null");
}
return context;
}
private Bitmap getBitmap() {
if (bitmap != null) {
return bitmap;
} else if (view instanceof TextureView) {
bitmap = ((TextureView) view).getBitmap();
Canvas canvas = new Canvas(bitmap);
view.draw(canvas);
canvas.setBitmap(null);
return bitmap;
} else {
bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
view.draw(canvas);
canvas.setBitmap(null);
return bitmap;
}
}
/**
* save() runs in a asynchronous thread
*
* @throws NullPointerException if View is null.
*/
public void save() throws NullPointerException {
if (view instanceof SurfaceView) {
PixelCopyHelper.getSurfaceBitmap((SurfaceView) view, new PixelCopyHelper.PixelCopyListener() {
@Override
public void onSurfaceBitmapReady(Bitmap surfaceBitmap) {
new BitmapSaver(getContext(), surfaceBitmap, printStackTrace, path, filename, fileExtension, jpgQuality, listener).execute();
}
@Override
public void onSurfaceBitmapError(String errorMsg) {
listener.onQuickShotFailed(path, errorMsg);
}
});
} else {
new BitmapSaver(getContext(), getBitmap(), printStackTrace, path, filename, fileExtension, jpgQuality, listener).execute();
}
}
public interface QuickShotListener {
void onQuickShotSuccess(String path);
void onQuickShotFailed(String path, String errorMsg);
}
static class BitmapSaver extends AsyncTask {
private final WeakReference weakContext;
private Handler mainThreadHandler = new Handler(Looper.getMainLooper());
private boolean printStacktrace;
private int jpgQuality;
private String errorMsg;
private String path;
private String filename;
private String fileExtension;
private Bitmap bitmap;
private File file;
private QuickShotListener listener;
BitmapSaver(Context context, Bitmap bitmap, boolean printStacktrace, String path, String filename, String fileExtension, int jpgQuality, QuickShotListener listener) {
this.weakContext = new WeakReference<>(context);
this.bitmap = bitmap;
this.printStacktrace = printStacktrace;
this.path = path;
this.filename = filename;
this.fileExtension = fileExtension;
this.jpgQuality = jpgQuality;
this.listener = listener;
}
/**
* @deprecated
*/
private void saveLegacy() {
if (path == null) {
path = Environment.getExternalStorageDirectory() + File.separator + DIRECTORY_PICTURES;
}
File directory = new File(path);
directory.mkdirs();
file = new File(directory, filename + fileExtension);
try (OutputStream out = new BufferedOutputStream(new FileOutputStream(file))) {
switch (fileExtension) {
case EXTENSION_JPG:
bitmap.compress(Bitmap.CompressFormat.JPEG, jpgQuality, out);
break;
case EXTENSION_PNG:
bitmap.compress(Bitmap.CompressFormat.PNG, 0, out);
break;
}
} catch (Exception e) {
if (printStacktrace) {
e.printStackTrace();
}
errorMsg = e.toString();
cancel(true);
} finally {
bitmap = null;
}
}
@RequiresApi(Build.VERSION_CODES.Q)
private void saveScopedStorage() {
path = path != null ? (DIRECTORY_PICTURES + File.separator + path) : DIRECTORY_PICTURES;
ContentValues contentValues = new ContentValues();
contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, filename);
contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, path);
contentValues.put(MediaStore.MediaColumns.MIME_TYPE, QuickShotUtils.getMimeType(fileExtension));
ContentResolver resolver = weakContext.get().getContentResolver();
Uri imageUri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
if (imageUri == null) {
errorMsg = String.format("Couldn't insert ContentValues with data: [%s] into the ContentResolver", contentValues.toString());
cancel(true);
return;
}
try (OutputStream out = resolver.openOutputStream(imageUri)) {
switch (fileExtension) {
case EXTENSION_JPG:
bitmap.compress(Bitmap.CompressFormat.JPEG, jpgQuality, out);
break;
case EXTENSION_PNG:
bitmap.compress(Bitmap.CompressFormat.PNG, 0, out);
break;
}
file = new File(path, filename + fileExtension);
} catch (Exception e) {
if (printStacktrace) {
e.printStackTrace();
}
errorMsg = e.toString();
resolver.delete(imageUri, null, null);
cancel(true);
} finally {
bitmap = null;
}
}
@Override
protected Void doInBackground(Void... voids) {
if (QuickShotUtils.isAboveAPI29()) {
saveScopedStorage();
} else {
saveLegacy();
}
return null;
}
@Override
protected void onPostExecute(Void v) {
listener.onQuickShotSuccess(file.getAbsolutePath());
if (!QuickShotUtils.isAboveAPI29()) {
MediaScannerConnection.scanFile(weakContext.get(), new String[]{file.getAbsolutePath()}, null, null);
}
}
@Override
protected void onCancelled() {
mainThreadHandler.post(new Runnable() {
@Override
public void run() {
listener.onQuickShotFailed(file.getAbsolutePath(), errorMsg);
}
});
}
}
}
================================================
FILE: quickshot/src/main/java/io/github/muddz/quickshot/QuickShotUtils.java
================================================
package io.github.muddz.quickshot;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.view.View;
import androidx.recyclerview.widget.RecyclerView;
import java.io.File;
class QuickShotUtils {
static String getMimeType(String src) {
src = src.substring(1);
if (src.equals("jpg")) {
src = "jpeg";
}
return "image" + File.separator + src;
}
static boolean isAboveAPI29() {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q;
}
private Bitmap generateLongBitmap(RecyclerView recyclerView) {
int itemCount = recyclerView.getAdapter().getItemCount();
RecyclerView.ViewHolder viewHolder = recyclerView.getAdapter().createViewHolder(recyclerView, 0);
//Measure the sizes of list item views to find out how big itemView should be
viewHolder.itemView.measure(View.MeasureSpec.makeMeasureSpec(recyclerView.getWidth(), View.MeasureSpec.EXACTLY), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
// Define measured widths/heights
int measuredItemHeight = viewHolder.itemView.getMeasuredHeight();
int measuredItemWidth = viewHolder.itemView.getMeasuredWidth();
//Set width/height of list item views
viewHolder.itemView.layout(0, 0, measuredItemWidth, measuredItemHeight);
//Create the Bitmap and Canvas to draw on
Bitmap recyclerViewBitmap = Bitmap.createBitmap(recyclerView.getMeasuredWidth(), measuredItemHeight * itemCount, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(recyclerViewBitmap);
//Draw RecyclerView Background:
if (recyclerView.getBackground() != null) {
Drawable drawable = recyclerView.getBackground().mutate();
drawable.setBounds(measuredItemWidth, measuredItemHeight * itemCount, 0, 0);
drawable.draw(canvas);
}
//Draw all list item views
int viewHolderTopPadding = 0;
for (int i = 0; i < itemCount; i++) {
recyclerView.getAdapter().onBindViewHolder(viewHolder, i);
viewHolder.itemView.setDrawingCacheEnabled(true);
viewHolder.itemView.buildDrawingCache();
canvas.drawBitmap(viewHolder.itemView.getDrawingCache(), 0f, viewHolderTopPadding, null);
viewHolderTopPadding += measuredItemHeight;
viewHolder.itemView.setDrawingCacheEnabled(false);
viewHolder.itemView.destroyDrawingCache();
// //TODO This should work but doesn't
// recyclerView.getAdapter().onBindViewHolder(viewHolder, i);
// viewHolder.itemView.draw(canvas);
// canvas.drawBitmap(recyclerViewBitmap, 0f, viewHolderTopPadding, null);
// viewHolderTopPadding += measuredItemHeight;
}
return recyclerViewBitmap;
}
}
================================================
FILE: readme.md
================================================
# QuickShot
[](https://android-arsenal.com/api?level=19)
[](https://github.com/Muddz/QuickShot/blob/master/QuickShotDemo.apk?raw=true)
An Android library that saves any `View`, `SurfaceView` or `Bitmap` as an image in `JPG`,`PNG` or `.nomedia`.
The library works on a asynchronous thread and handles errors and memory for you.
### Features
- Support for Android API 29+ and scoped storage
- Save in `JPG`,`PNG` or `.nomedia`.
- Save `Bitmap`, `View` or `SurfaceView` objects as images
- Set a path and filename for your captures or resort to auto defaults
- Asynchronous saving
## Example of simplest usage with defaults
You can use a simple one-liner and let QuickShot set default values like in the following example:
Filename defaults to a timestamp.
Path defaults to `/Pictures` in internal storage.
Image format defaults to `.JPG`
```java
QuickShot.of(view).setResultListener(this).save();
```
## Example of a detailed usage
```java
QuickShot.of(view).setResultListener(this)
.enableLogging()
.setFilename("QuickShot")
.setPath("MyApp")
.toPNG()
.save();
```
## Installation
Add the dependency in your `build.gradle`
```groovy
dependencies {
implementation 'io.github.muddz:quickshot:1.4.0'
}
```
----
## License
Copyright 2018 Muddi Walid
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
================================================
FILE: settings.gradle
================================================
include ':demo', ':quickshot'