so let's start
1.create a menu folder inside res Folder and inside menu folder create a menu file and name it like navigation_menu and paste this code
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/gpg_to_png"
android:title="JPG to PNG"/>
</menu>
2. I give some id in activity_main.xml here is the code
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/drawerLayout"
tools:context=".MainActivity">
<com.google.android.material.navigation.NavigationView
android:id="@+id/navigationSlide"
android:layout_width="wrap_content"
android:layout_height="match_parent"
app:menu="@menu/navigation_menu"
android:layout_gravity="start" />
<androidx.coordinatorlayout.widget.CoordinatorLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/white"
android:fitsSystemWindows="true"
android:theme="@style/Theme.Convertor">
<com.google.android.material.appbar.CollapsingToolbarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fitsSystemWindows="true"
app:contentScrim="@color/white"
app:expandedTitleGravity="top"
app:expandedTitleMarginStart="48dp"
app:expandedTitleMarginTop="7dp"
app:layout_scrollFlags="scroll|snap|exitUntilCollapsed"
app:title="img to pdf">
<include
layout="@layout/convertor_toll"
app:layout_collapseMode="parallax" />
<androidx.appcompat.widget.Toolbar
android:id="@+id/mainToolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:layout_collapseMode="pin"
app:navigationIcon="@drawable/ic_baseline_menu_24"
app:title="img to pdf" />
</com.google.android.material.appbar.CollapsingToolbarLayout>
</com.google.android.material.appbar.AppBarLayout>
<androidx.core.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_behavior="com.google.android.material.appbar.AppBarLayout$ScrollingViewBehavior">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/pdf_recyclerView"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</androidx.core.widget.NestedScrollView>
<ProgressBar
android:id="@+id/progressBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="300dp"
android:visibility="gone" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>
</androidx.drawerlayout.widget.DrawerLayout>
3.update your MainActivity.java code
public class MainActivity extends AppCompatActivity {
private static final int REQUEST_CODE = 100;
public static String folderPath = Environment.getDataDirectory().getAbsolutePath()
+ "/storage/emulated/0/your_folder_name";
public static File directory = new File("/sdcard/your_folder_name/");
Button camera, upload, convert;
ImageView img;
TextView title;
ProgressBar progressBar;
ArrayList<Model> pdfList = new ArrayList<>();
RecyclerView recyclerView;
FileAdapter fileAdapter;
Toolbar toolbar;
DrawerLayout drawerLayout;
NavigationView navigationView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
askPermission();
camera = findViewById(R.id.convertor_toll_camera);
upload = findViewById(R.id.convertor_toll_upload);
convert = findViewById(R.id.convertor_toll_convert);
img = findViewById(R.id.convertor_toll_imageView);
title = findViewById(R.id.convertor_toll_fileName);
progressBar = findViewById(R.id.progressBar);
recyclerView = findViewById(R.id.pdf_recyclerView);
camera.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (directory.exists()) {
progressBar.setVisibility(View.VISIBLE);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CODE);
} else {
progressBar.setVisibility(View.GONE);
Toast.makeText(MainActivity.this, "try again",
Toast.LENGTH_SHORT).show();
createFolder();
}
}
});
upload.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (directory.exists()) {
progressBar.setVisibility(View.VISIBLE);
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, REQUEST_CODE);
} else {
progressBar.setVisibility(View.GONE);
Toast.makeText(MainActivity.this, "try again",
Toast.LENGTH_SHORT).show();
createFolder();
}
}
});
toolbar = findViewById(R.id.mainToolbar);
drawerLayout = findViewById(R.id.drawerLayout);
navigationView = findViewById(R.id.navigationSlide);
setSupportActionBar(toolbar);
navigationView.bringToFront();
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
if (item.getItemId() == R.id.gpg_to_png){
drawerLayout.closeDrawer(GravityCompat.START);
startActivity(new Intent(MainActivity.this, JPEGTOPNGActivity.class));
}
return false;
}
});
loadPDFFiles();
}
@RequiresApi(api = Build.VERSION_CODES.O)
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
progressBar.setVisibility(View.GONE);
if (data != null) {
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA,
MediaStore.Images.Media.DISPLAY_NAME};
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn,
null, null);
cursor.moveToFirst();
int filePath = cursor.getColumnIndex(filePathColumn[0]);
int fileName = cursor.getColumnIndex(filePathColumn[1]);
String path = cursor.getString(filePath);
String name = cursor.getString(fileName);
cursor.close();
img.setImageURI(Uri.parse(path));
title.setText(name);
convert.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
progressBar.setVisibility(View.VISIBLE);
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
boolean converted = imageToPDF(path, name);
runOnUiThread(new Runnable() {
@Override
public void run() {
progressBar.setVisibility(View.GONE);
if (!converted) {
Toast.makeText(MainActivity.this, "fail",
Toast.LENGTH_SHORT).show();
}
}
});
}
});
thread.start();
}
});
} else {
Toast.makeText(this, "select a image",
Toast.LENGTH_SHORT).show();
}
}
private void askPermission() {
if (ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.WRITE_EXTERNAL_STORAGE)
+ ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.CAMERA}, REQUEST_CODE);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
@NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_CODE) {
createFolder();
}
}
public static void createFolder() {
File folder = new File(folderPath);
if (!folder.exists()) {
folder.mkdir();
}
directory.mkdirs();
}
private boolean imageToPDF(String path, String name) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
Bitmap bitmap = BitmapFactory.decodeFile(path);
PdfDocument pdfDocument = new PdfDocument();
PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(
1970, 4160, 0).create();
PdfDocument.Page page = pdfDocument.startPage(pageInfo);
page.getCanvas().drawBitmap(bitmap, 0, 0, null);
pdfDocument.finishPage(page);
String changeName = getWithoutExtension(name);
String newPath = directory + "/" + changeName + ".pdf";
File file = new File(newPath);
try {
pdfDocument.writeTo(new FileOutputStream(file));
MediaScannerConnection.scanFile(MainActivity.this,
new String[]{file.toString()}, null, null);
} catch (Exception e) {
e.getStackTrace();
}
pdfDocument.close();
return true;
} else {
return false;
}
}
public static String getWithoutExtension(String name) {
return name.substring(0, name.lastIndexOf("."));
}
private void loadPDFFiles() {
pdfList = loadFiles(this);
fileAdapter = new FileAdapter(this, pdfList);
recyclerView.setAdapter(fileAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this,
RecyclerView.VERTICAL, false));
}
public ArrayList<Model> loadFiles(Context context) {
ArrayList<Model> arrayList = new ArrayList<>();
Uri uri = MediaStore.Files.getContentUri("external");
String[] projection = {
MediaStore.Files.FileColumns._ID,
MediaStore.Files.FileColumns.DATA,
MediaStore.Files.FileColumns.TITLE,
MediaStore.Files.FileColumns.SIZE,
MediaStore.Files.FileColumns.MIME_TYPE,
};
String mimeType = "application/pdf";
String whereClause = MediaStore.Files.FileColumns.MIME_TYPE + " IN ('" + mimeType + "')";
String sortOrder = MediaStore.Files.FileColumns.DATE_ADDED + " DESC";
Cursor cursor = context.getContentResolver().query(uri, projection, whereClause,
null, sortOrder);
int idColumn = cursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns._ID);
int idPath = cursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns.DATA);
int idTitle = cursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns.TITLE);
int idSize = cursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns.SIZE);
if (cursor != null) {
while (cursor.moveToNext()) {
String id = cursor.getString(idColumn);
String path = cursor.getString(idPath);
String title = cursor.getString(idTitle);
long size = cursor.getLong(idSize);
Model model = new Model(id, title, path, convertIntoReadableSize(size));
arrayList.add(model);
}
}
return arrayList;
}
private String convertIntoReadableSize(long size) {
String s = "";
long kilo = 1024;
long mega = kilo * kilo;
long giga = mega * kilo;
long tera = giga * kilo;
double kb = (double) size / kilo;
double mb = kb / kilo;
double gb = mb / kilo;
double tb = gb / kilo;
if (size < kilo) {
s = size + " Bytes";
} else if (size >= kilo && size < mega) {
s = String.format("%.2f", kb) + " KB";
} else if (size >= mega && size < giga) {
s = String.format("%.2f", mb) + " MB";
} else if (size >= giga && size < tera) {
s = String.format("%.2f", gb) + " GB";
} else if (size >= tera) {
s = String.format("%.2f", tb) + " TB";
}
return s;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
boolean isOpen = drawerLayout.isDrawerOpen(GravityCompat.START);
if (item.getItemId() == android.R.id.home){
if (isOpen){
drawerLayout.closeDrawer(GravityCompat.START);
}else {
drawerLayout.openDrawer(GravityCompat.START);
}
}
return super.onOptionsItemSelected(item);
}
}
4.Create new Activity and name it like JPEGTOPNGActivity
A. Open activity_jpegtopngactivity.xml and add this code
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".JPEGTOPNGActivity">
<include
android:id="@+id/include"
layout="@layout/convertor_toll" />
<ProgressBar
android:visibility="gone"
android:id="@+id/jpgtopngProgressBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
B. Open JPEGTOPNGActivity.java and add this code
public class JPEGTOPNGActivity extends AppCompatActivity {
ImageView imageView;
Button camera, upload, convert;
Space space;
TextView textView;
ProgressBar progressBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_jpegtopngactivity);
camera = findViewById(R.id.convertor_toll_camera);
camera.setVisibility(View.GONE);
space = findViewById(R.id.space);
space.setVisibility(View.GONE);
upload = findViewById(R.id.convertor_toll_upload);
convert = findViewById(R.id.convertor_toll_convert);
imageView = findViewById(R.id.convertor_toll_imageView);
progressBar = findViewById(R.id.jpgtopngProgressBar);
textView = findViewById(R.id.convertor_toll_fileName);
upload.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (directory.exists()){
progressBar.setVisibility(View.VISIBLE);
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, 88);
}else {
progressBar.setVisibility(View.GONE);
Toast.makeText(JPEGTOPNGActivity.this, "try again",
Toast.LENGTH_SHORT).show();
createFolder();
}
}
});
}
@RequiresApi(api = Build.VERSION_CODES.O)
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
progressBar.setVisibility(View.GONE);
if (data!=null){
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA,
MediaStore.Images.Media.DISPLAY_NAME};
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn,
null, null);
cursor.moveToFirst();
int filePath = cursor.getColumnIndex(filePathColumn[0]);
int fileName = cursor.getColumnIndex(filePathColumn[1]);
String path = cursor.getString(filePath);
String name = cursor.getString(fileName);
cursor.close();
if (requestCode == 88){
imageView.setImageURI(Uri.parse(path));
textView.setText(name);
convert.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
progressBar.setVisibility(View.VISIBLE);
useAnotherThread(path,name);
}
});
}
}else {
Toast.makeText(this, "select image",
Toast.LENGTH_SHORT).show();
}
super.onActivityResult(requestCode, resultCode, data);
}
private void useAnotherThread(String path, String name) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
boolean isConverted = convertIntoPNG(path, name);
runOnUiThread(new Runnable() {
@Override
public void run() {
progressBar.setVisibility(View.GONE);
if (isConverted){
Toast.makeText(JPEGTOPNGActivity.this, "Converted",
Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(JPEGTOPNGActivity.this, "Fail to Convert",
Toast.LENGTH_SHORT).show();
}
}
});
}
});
thread.start();
}
private boolean convertIntoPNG(String path, String name) {
Bitmap bitmap = BitmapFactory.decodeFile(path);
String changeName = getWithoutExtension(name);
String newPath = directory + "/" + changeName + ".png";
try {
FileOutputStream fileOutputStream = new FileOutputStream(newPath);
bitmap.compress(Bitmap.CompressFormat.PNG,100, fileOutputStream);
fileOutputStream.close();
}catch (IOException e){
e.printStackTrace();
return false;
}
return true;
}
}
5. if you are facing errors like manifest merge fail then open your graddle.properties and add these 2lines of code
# Project-wide Gradle settings.
# IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
# org.gradle.parallel=true
# AndroidX package structure to make it clearer which packages are bundled with the
# Android operating system, and which are packaged with your app"s APK
# https://developer.android.com/topic/libraries/support-library/androidx-rn
android.useAndroidX=true
android.enableJetifier=true
Watch Full Tutorials
0 Comments