Trending February 2024 # How To Compress An Image’S File Size Dramatically And Still Maintain Quality. # Suggested March 2024 # Top 2 Popular

You are reading the article How To Compress An Image’S File Size Dramatically And Still Maintain Quality. updated in February 2024 on the website Kientrucdochoi.com. We hope that the information we have shared is helpful to you. If you find the content interesting and meaningful, please share it with your friends and continue to follow and support us for the latest updates. Suggested March 2024 How To Compress An Image’S File Size Dramatically And Still Maintain Quality.

In a world where gigabytes and terabytes are the main units of storage, compressing and shrinking the file size of images and photos might seem a little pointless. This might be the case if you are storing files on your computer’s hard drive but if your phone is starting to fill up or your cloud space is nearing its capacity, image compression is a very attractive option. Even more enticing is fact that there are ways to compress images in bulk.

How to Find and Remove Stalkerware From your Computer or Mobile Device.

Shrink Image File Sizes Without Ruining Quality. (Program Based Compression)

Whatever your reason for wanting to reduce the size of your images, below are some programs that offer very good image compression rates, whilst maintaining quality. First on the list is Caesium Image Compressor, which is available on Windows. Caesium allows you to reduce/compress the size of multiple image formats including PNG. JPG, JPEG, and GIF files, as well as a few other less common types. It also claims to be able to reduce an image’s size by up to 90%, which is huge! If 90% is way too much, the option to manually choose a setting is also available. A setting between 50% – 80% works best.

Download Caesium Image Compressor.

Download ImageOptim.

The final program based Image compressor is called Trimage and is for users running Linux (it’s available on other OS too) Trimage is by far the most difficult image compressor to use as it is command line based. For most users this will be a turnoff, however, if you are a frequent Linus user or are familiar with using similar programs, Trimage is a great choice and the compression quality is exceptional.

Download Trimage

Shrink Image File Sizes Without Ruining Quality (Web Browser)

If you only need to shrink a few images every so often and don’t mind a slightly longer process, you can use Image compression websites. Image compression websites allow you to upload an image to be compressed, then redownload it in a smaller more compact file size. The quality of online image compression services varies quite a lot, so you may need to try a few different websites before you find one that you like.

You're reading How To Compress An Image’S File Size Dramatically And Still Maintain Quality.

How To Crop An Image Along The Y

In this tutorial, we are going to learn how to crop an image along the y-axis using FabricJS. We can create an Image object by creating an instance of fabric.Image. Since it is one of the basic elements of FabricJS, we can also easily customize it by applying properties like angle, opacity etc. In order to crop an image along the y-axis, we use the cropY property.

Syntax Parameters

element − This parameter accepts HTMLImageElement, HTMLCanvasElement, HTMLVideoElement or String which denotes the image element. The String should be a URL and would be loaded as an image.

options (optional) − This parameter is an Object which provides additional customizations to our object. Using this parameter origin, stroke width and a lot of other properties can be changed related to the image object of which cropY is a property.

callback (optional) − This parameter is a function which is to be called after eventual filters are applied.

Options Keys

cropY − This property accepts a Number value which denotes the image crop in pixels along the y-axis, from the original image size.

Default appearance of Image object Example

Let’s see a code example of how the Image object appears when cropY property is not used. As we can see, there is no image crop along the y-axis.

var

canvas

=

new

fabric

.

Canvas

(

“canvas”

)

;

canvas

.

setWidth

(

document

.

body

.

scrollWidth

)

;

canvas

.

setHeight

(

250

)

;

var

imageElement

=

document

.

getElementById

(

“img1”

)

;

var

image

=

new

fabric

.

Image

(

imageElement

,

{

top

:

50

,

left

:

110

,

}

)

;

canvas

.

add

(

image

)

;

Using the cropY property Example

In this example, we have used the cropY property and assigned it a number value of 25. Therefore, the image crop is 25 pixels along the y-axis.

var

canvas

=

new

fabric

.

Canvas

(

“canvas”

)

;

canvas

.

setWidth

(

document

.

body

.

scrollWidth

)

;

canvas

.

setHeight

(

250

)

;

var

imageElement

=

document

.

getElementById

(

“img1”

)

;

var

image

=

new

fabric

.

Image

(

imageElement

,

{

top

:

50

,

left

:

110

,

cropY

:

25

,

}

)

;

canvas

.

add

(

image

)

;

Conclusion

In this tutorial, we used two examples to demonstrate how you can crop an Image along the Y-axis using FabricJS.

How To Pixelate An Image On Windows And Mac

There are a number of reasons why you might want to pixelate part or all of an image. If you’re touching up a family photo to post online, you may want to pixelate the faces of some of your family members. If you’re editing a scanned image, you may want to pixelate some personal data to protect yourself before posting it online.

There are several ways you can quickly pixelate an image on Windows and Mac using various free or paid photo editors, such as Photoshop and GIMP, or by using online services to edit your images. If you want to know how to pixelate an image, here’s what you’ll need to do.

Table of Contents

[1-Pixelate-Image-Featured.png]

ΩHow to Pixelate Images Using Photos on Mac

The easiest way to pixelate images is to use the tools you already have at your disposal. If you’re a Mac user, this means using the built-in Photos app to pixelate your images quickly.

Photos is pre-installed on all Macs, so you don’t need to install anything extra to begin. You can launch Photos from the Applications folder in the Finder app or from the Launchpad via the Dock instead.

The image editing options will appear on the right-hand side of the Photos app. While Photos doesn’t have a built-in pixelation tool, you can use the retouch tool to achieve a similar effect. Move the retouch slider to increase the effect, select the checkbox to activate it, then apply the effect using your mouse to the area you want to hide.

You can preview the slider effect on the right. If you’re unhappy, select Revert to Original in the top menu bar, or select Done to save the changes.

How to Pixelate Images Using Paint 3D on Windows

The Paint 3D tool is a replacement for Microsoft Paint, created by Microsoft to introduce new features (such as basic 3D modelling) that aren’t possible in the original software.

One useful feature of Paint 3D, however, is a quick pixelation tool for images. Paint 3D should be pre-installed on your Windows PC but, if it isn’t, you can download and install it from the Microsoft Store.

Once the file is open, use the Select tool to select the portion of the image you want to pixelate (or select the whole image to pixelate the entire image). Once selected, reduce the selected portion of the image in size—this will reduce the quality of the selected portion of the image.

Using Adobe Photoshop to Pixelate Images on Windows or Mac

While Adobe Photoshop is one of the best and well known professional photo editors for Windows and Mac users, it can also handle pretty simple tasks like image pixelation.

Using the Select tool, select the portion of your image that you want to pixelate. If you want to pixelate the entire image, proceed to the next step.

In the Pixelate box, move the Cell Size slider to increase the pixelation effect. Select OK to apply it.

Using GIMP to Pixelate Images on Windows or Mac

If you want to pixelate images using free software, you can use the open source GIMP to do it. This free photo editor is available for Windows and Mac, as well as other platforms like Linux.

In the Pixelise box, increase or decrease the pixelation effect by changing the Block weight and Block weight values. To apply the effect, select OK.

Using Adobe Photoshop Express to Pixelate Images Online

If you want to pixelate images quickly without installing a third-party app, you can use an online photo editor. Various websites exist, but one of the best is to use Adobe Photoshop Express, which will allow you to pixelate an entire image.

To start, upload an image to the Adobe Photoshop Express website by selecting the Upload file option.

Once the image is loaded, select Art effects on the right, then select the Effects category in the Art effects tab on the right. 

Select the Pixelate effect to apply it to the image and move the Pixel size slider to increase or decrease the effect. Select Apply to apply the change.

Once the effect is applied, download the image by selecting the Download option at the top.

Better Photo Editing on Windows and Mac

Now you know how to pixelate images on Windows and Mac, you can take your photo editing to the next level. For instance, you may want to restore old photos using tools like GIMP or create high-resolution vector images using Inkscape or Adobe Illustrator. 

How To Compress A Video In Windows 11

Are you getting “File is too large” error when you try to send a video to someone via a sharing or social platform? Or do you just want to save your disk space by reducing the file size of your video files? This guide will show you several methods on how to compress a video to reduce its file size in Windows 11.

The most common practice of reducing the file size of a video is reduce the video resolution. Raw video recorded using a camera or screen recorder usually has a very large resolution. If the video is to be seen on a rather smaller device, you can reduce its resolution to a smaller size such as 720p, 480p, etc. to significantly reduce its file size.

Some video players and apps will allow you to export a video with a different resolution. In Windows 11, you can use the built-in Photos app’s Video Editor feature to change the resolution of a video. Alternatively, you can also use a third party software such as VLC player to convert a video to a different resolution, but with much more choices of video resolutions.

Follow the steps below to change a video resolution using Photos app in Windows 11.

1. First, search for and open Video Editor via Start.

4. To edit the video, drag the video from the Project library to the are where it says “Drag items from the project library here”.

VLC media player is a popular media player that supports a wide range of audio and video formats. But did you know that you can also use VLC player to compress videos? With VLC player, you can easily compress your videos without sacrificing too much quality.

3. Next, select a Profile that best describe on what device the video will be viewed on. For example, if you select the “Video for iPod HD/iPhone/PSP” profile, VLC will convert the video to 480p along with other settings that best suited to be viewed on an iPhone, which will significantly reduce the video file size if the original resolution is rather large.

Trimming a video means to remove unwanted parts of the video to create a clip out of it. Doing so will reduce the video’s total file size as the video gets shortened. You can trim a video file using any video editor. In Windows 11, you can use the Photo’s app built-in Video Editor feature to trim a video without installing any third party software.

To learn how to do so, go to: How to edit and trim a video in Windows 11.

ZIP is a file format that supports lossless data compression. You can compress your video files by compressing it using Zip, or other compression formats such as RAR or 7Zip.

In the Add to archive window, select a compression level. The higher the compression level (“Ultra” being the highest level), the better the compression and the smaller the file size after compressed.

If a video is too large in size that there is no way to compress it small enough to fit into the sharing platform such as Facebook, WhatsApp, etc., you can upload your video file onto a file sharing service such as Google Drive or Dropbox, and then send the video link to whoever you want to share with so that they can download it using the link.

Since the file size limit for individual file you can upload to these sharing services is usually very large, you can upload your original video or compressed video without the concern of file size limit.

Alternatively, you can also upload your video directly to YouTube and share the video only with whoever you want to share with by setting the video as “unlisted” or “private”.

How To Use The Zip Command In Linux To Compress Files And Folders

The zip command in Linux is probably the simplest and most intuitive way to work with ZIP files on the command line. And not just that, the ZIP file format is universal – almost every OS out there has a native program that can work with it. Here’s all the ways you can use this command in any Linux command line.

How to Install Zip in Linux

The latest version of the Linux zip command should be available in all major package managers.

For Debian/Ubuntu:

sudo

apt

install

zip

For Arch Linux:

sudo

pacman

-S

zip

For Fedora:

sudo

dnf

install

zip

For Gentoo

sudo

emerge

--ask

zip

Note: Before installing anything, make sure to update your package manager first to get the zip command’s latest version. You can learn how to do that and more with our Linux package manager cheatsheet.

Note: With zip installed, the unzip command will also be available now.

Zip Command in Linux: Syntax and Options

There’s a basic syntax to the zip command, and it takes just two parameters: the output ZIP file’s filename and the input’s filename.

As for setting the options, you’ll need to work with flags. There are 8 flags you would regularly need for normal use:

-d delete selected archived entries in the ZIP file.

-q quietly do task without printing anything on the terminal.

-T test the ZIP file’s integrity.

-e encrypt file.

-u update ZIP file by adding new files into the archive.

-m move file into archive.

-r recursively add files within a folder into a ZIP file.

-x exclude files with the selected filenames.

-i include only files with the selected names.

You can place the flags anywhere you like whether they’re before the output, after the input, between the two – you can even use multiple flags scattered all around the line in any order. Just make sure that you type them after typing zip.

The exception are -x and -i which need a new input after using them.

How to Zip a File in Linux Using the Zip Command

The easiest way to archive files with the zip command is to type zip followed by the filename of the ZIP file and then the file you are trying to archive or compress. Flags are optional, so you can do it like that to quickly zip any file on Linux.

zip

chúng tôi text_file.txt

You can also add more files by adding the others after the first file you were trying to archive. And if any of these have spaces in their names, you can enclose them in quotation marks.

zip

chúng tôi

"file 1.txt"

"file 2.txt"

"file 3.txt"

"file 4.txt"

Using the -d Flag

The -d flag lets you delete a file archived within the ZIP file in the same way you would have added it into one.

zip

-d

chúng tôi remove_me.jpg

You can also use it to remove entire folders within the archive. However, this won’t work for files outside of the ZIP file (so you can’t use it to delete files after archiving).

Using the -q Flag

The -q flag is for making sure that zip won’t return a message when it does its thing.

zip

-q

chúng tôi text_file.txt

It’s useful when you’re using the zip command with a script. But if you’re using this by yourself, you might want to avoid using the -q flag since you won’t know if the the archiving process was successful without checking with the dir or ls command.

Using the -T Flag

Some files Some ZIP files can get corrupted during download – it happens. You can use the -T flag to check the integrity so you would know if it really is a broken file or you’re just inputting the wrong password.

zip

-T

chúng tôi is pretty important when downloading large files like OS images. For files like these, you can successfully burn them into a live USB and end up with errors once you run the image file on your machine. The same goes with videos and music that get cut-up parts in random places.

Using the -u Flag

If you wanted to add a new file into an existing ZIP file, you can use the -u flag.

zip

-u

chúng tôi new_file.txt

You can also add more files by adding them after the first file, as if you were using the zip command normally to make a new ZIP archive.

Using the -e Flag

If you want to add a password, you need to use the -e flag. This option only applies the password and encryption into the file you add into the ZIP file within its command, so previous files will remain unencrypted if you use this with the -u flag.

zip

-e

chúng tôi text_file.txt

The great thing about ZIP files is that the password-making process also adds an extra layer of protection besides giving access. Your password works like a digital signature which is used to decrypt an extra encryption layer added into the ZIP file.

Using the -m Flag

Lastly, the -m flag deletes the original file after it gets archived into the ZIP file. Think of this as automating an extra step so you won’t have to remove it by yourself.

zip

-m

chúng tôi text_file.txt

One important bit to remember though: the -m flag deletes files in such a way that makes it impossible to recover them without using a file restoration tool. So be sure to keep a backup, or just remove things manually using the rm command instead.

How to Zip a Folder in Linux Using the Zip Command

If you use the zip command on a raw folder, you’ll be left with a folder that does not contain any files at all. Whenever you are trying to zip a folder, you need to use the -r flag.

Using the -r Flag

The -r flag, aka recursive, goes through each content of a folder and its subfolders and archives every single one into the ZIP file. It will also retain the current structure of each subfolder.

zip

-r

chúng tôi my_folder

This also works if you want to archive everything within the current folder. Just replace my_folder with ./ and it will change its target to everything within the current one.

zip

-r

chúng tôi .

/

Furthermore, you can use this alongside the -u flag to include folders and their contents into an existing ZIP file.

zip

-r

-u

chúng tôi another_folder Using the -i Flag

The -i flag lets you pick out a specific file that you want to include and excludes everything else within a folder

zip

-r

chúng tôi my_folder

-i

my_folder

/

a_subfolder

/

file1.txt

By using * asterisks with the -i flag, you can select files that share similar names but could end with something like a number. For example, typing *.txt will make the zip command include all TXT files within the folder.

zip

-r

chúng tôi my_folder

-i

"*.txt"

Using the -x Flag

The -x flag lets you exclude only certain files while zipping a whole folder.

zip

-r

chúng tôi my_folder

-x

my_folder

/

dont_zip.jpg

Also, the -x flag overrides the -i flag when used together. This way, you can, for example, tell zip to include all the other files of the same type except for the file you don’t want it to zip.

zip

-r

chúng tôi my_folder

-i

"*.txt"

-x

my_folder

/

dont_zip.txt How to Unzip a File Using the Linux Zip Command

The unzip program is a partner program to the default zip program. It extracts files from your ZIP archive.

To use this program, you just need to type unzip and the filename of the ZIP archive.

unzip

chúng tôi using the unzip command, you will unzip the ZIP file within the current working directory regardless of where the ZIP file came from.

To extract or unzip a Linux file within a ZIP file so the others remain unextracted, you can add its filename after the part where you type the archive.

unzip

chúng tôi chúng tôi to Unzip a Linux Folder With Zip

While unzip will normally extract folders located within a ZIP archive, it can be pretty hard to make it extract only certain folders. But that does not mean it’s impossible.

unzip

chúng tôi my_folder

/

a_subfolder

/*

That line of code extracts everything within a_subfolder.

Also, when you unzip a folder, the unzip program creates a new folder within the current working directory and unpacks its folders there. If a folder exists with the same name (or a previous version of the folder is present), it ask if it’s okay to replace the file that’s currently in the folder.

Frequently Asked Questions What does the gzip command in Linux do?

The Linux gzip command is a tool that you can use to store and compress files into a GZ file.

Is ZIP better than TAR?

In a way, ZIP is better than TAR because ZIP files can compress, encrypt, and protect their contents. However, TAR files are meant to combine files into one file for faster file transfer while ZIP files (despite being used for the same purpose) come with those extra features in mind.

Is TAR faster than ZIP?

TAR files do not compress nor encrypt their contents. So if you are looking for a faster way to combine a large amount of files into a single easy-to-transfer archive, you’ll see some gains with TAR compared to ZIP. However, you might find it easier to transfer a ZIP file instead of a TAR file because ZIP files tend to be much smaller than TAR files.

Image credit: Unsplash, Screenshots by Terenz Jomar Dela Cruz

Terenz Jomar Dela Cruz

Terenz is a hobbyist roboticist trying to build the most awesome robot the world has ever seen. He could have done that already if he wasn't so busy burning through LEDs as a second hobby.

Subscribe to our newsletter!

Our latest tutorials delivered straight to your inbox

Sign up for all newsletters.

By signing up, you agree to our Privacy Policy and European users agree to the data transfer policy. We will not share your data and you can unsubscribe at any time.

Ml Kit Image Labeling: Determine An Image’s Content With Machine Learning

What is Image Labeling?

On device, or in the cloud?

There’s several benefits to using the on-device model:

It’s free – No matter how many requests your app submits, you won’t be charged for performing Image Labeling on-device.

It doesn’t require an Internet connection – By using the local Image Labeling model, you can ensure your app’s ML Kit features remain functional, even when the device doesn’t have an active Internet connection. In addition, if you suspect your users might need to process a large number of images, or process high-resolution images, then you can help preserve their mobile data by opting for on-device image analysis.

It’s faster – Since everything happens on-device, local image processing will typically return results quicker than the cloud equivalent.

Which are we using, and will I need to enter my credit card details?

In our app, we’ll be implementing both the on-device and cloud Image Labeling models, so by the end of this article you’ll know how to harness the full power of ML Kit’s cloud-based processing, and how to benefit from the real-time capabilities of the on-device model.

Although the cloud model is a premium feature, there’s a free quota in place. At the time of writing, you can perform Image Labeling on up to 1,000 images per month for free. This free quota should be more than enough to complete this tutorial, but you will need to enter your payment details into the Firebase Console.

If you don’t want to hand over your credit card information, just skip this article’s cloud sections — you’ll still end up with a complete app.

Create your project and connect to Firebase

To start, create a new Android project with the settings of your choice.

Since ML Kit is a Firebase service, we need to create a connection between your Android Studio project, and a corresponding Firebase project:

In your web browser, head over to the Firebase Console.

Select “Add project” and give your project a name.

Read the terms and conditions, and then select “I accept…” followed by “Create project.”

Select “Add Firebase to your Android app.”

Select “Download google-services.json.” This file contains all the necessary Firebase metadata.

In Android Studio, drag and drop the chúng tôi file into your project’s “app” directory.

Next, open your project-level build.gradle file and add Google Services:

Code

classpath 'com.google.gms:google-services:4.0.1'

Open your app-level build.gradle file, and apply the Google services plugin, plus the dependencies for ML Kit, which allows you to integrate the ML Kit SDK into your app:

Code

apply plugin: 'com.google.gms.google-services' … … … dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) implementation 'com.google.firebase:firebase-core:16.0.5' implementation 'com.google.firebase:firebase-ml-vision:18.0.1' implementation 'com.google.firebase:firebase-ml-vision-image-label-model:17.0.2'

To make sure all these dependencies are available to your app, sync your project when prompted.

Next, let the Firebase Console know you’ve successfully installed Firebase. Run your application on either a physical Android smartphone or tablet, or an Android Virtual Device (AVD).

Back in the Firebase Console, select “Run app to verify installation.”

Firebase will now check that everything is working correctly. Once Firebase has successfully detected your app, it’ll display a “Congratulations” message. Select “Continue to the console.”

On-device Image Labeling: Downloading Google’s pre-trained models

<application android:allowBackup=”true” android:icon=”@mipmap/ic_launcher” android:label=”@string/app_name” android:roundIcon=”@mipmap/ic_launcher_round” android:supportsRtl=”true” <meta-data android:name=”com.google.firebase.ml.vision.DEPENDENCIES”

Building our Image Labeling layout

I want my layout to consist of the following:

An ImageView – Initially, this will display a placeholder, but it’ll update once the user selects an image from their device’s gallery.

A “Device” button – This is how the user will submit their image to the local Image Labeling model.

A “Cloud” button – This is how the user will submit their image to the cloud-based Image Labeling model.

A TextView – This is where we’ll display the retrieved labels and their corresponding confidence scores.

A ScrollView – Since there’s no guarantee the image and all of the labels will fit neatly on-screen, I’m going to display this content inside a ScrollView.

Here’s my completed activity_main.xml file:

android:layout_width=”match_parent” android:layout_height=”match_parent” android:padding=”20dp” <ScrollView android:layout_width=”match_parent” android:layout_height=”match_parent” android:layout_alignParentTop=”true” <LinearLayout android:layout_width=”match_parent” android:layout_height=”wrap_content” <ImageView android:id=”@+id/imageView” android:layout_width=”match_parent” android:layout_height=”wrap_content” android:adjustViewBounds=”true” <Button android:id=”@+id/btn_device” android:layout_width=”match_parent” android:layout_height=”wrap_content” <TextView android:id=”@+id/textView” android:layout_width=”match_parent” android:layout_height=”wrap_content” android:layout_marginTop=”20dp” <Button android:id=”@+id/btn_cloud” android:layout_width=”match_parent” android:layout_height=”wrap_content”

Open the “Icon Type” dropdown and select “Action Bar and Tab Icons.”

Make sure the “Clip Art” radio button is selected.

Select the image that you want to use as your placeholder; I’m using “Add to photos.”

In the “Name” field, enter “ic_placeholder.”

Action bar icons: Choosing an image

Next, we need to create an action bar item, which will launch the user’s gallery, ready for them to select an image.

You define action bar icons inside a menu resource file, which lives inside a “res/menu” directory. If your project doesn’t already contain a “menu” directory, then you’ll need to create one:

Open the “Resource type” dropdown and select “menu.”

The “Directory name” should update to “menu” automatically, but if it doesn’t then you’ll need to rename it manually.

Next, create the menu resource file:

Name this file “my_menu.”

Open the “my_menu.xml” file, and add the following:

<item android:id=”@+id/action_gallery” android:orderInCategory=”102″ android:title=”@string/action_gallery” android:icon=”@drawable/ic_gallery”

Set the “Icon Type” dropdown to “Action Bar and Tab Icons.”

Choose a drawable; I’m using “image.”

To ensure this icon is clearly visible in your app’s action bar, open the “Theme” dropdown and select “HOLO_DARK.”

Name this icon “ic_gallery.”

Name this class “BaseActivity.”

Open BaseActivity and add the following:

Code

import android.Manifest; import android.content.Intent; import android.content.pm.PackageManager; import android.os.Bundle; import android.provider.MediaStore; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.ActivityCompat; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.view.Menu; import android.view.MenuItem; import java.io.File; public class BaseActivity extends AppCompatActivity { public static final int RC_STORAGE_PERMS1 = 101; public static final int RC_SELECT_PICTURE = 103; public static final String ACTION_BAR_TITLE = "action_bar_title"; public File imageFile; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setTitle(getIntent().getStringExtra(ACTION_BAR_TITLE)); } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.my_menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_gallery: checkStoragePermission(RC_STORAGE_PERMS1); break; } return super.onOptionsItemSelected(item); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); switch (requestCode) { case RC_STORAGE_PERMS1: selectPicture(); } else { MyHelper.needPermission(this, requestCode, R.string.permission_request); } break; } } public void checkStoragePermission(int requestCode) { switch (requestCode) { case RC_STORAGE_PERMS1: int hasWriteExternalStoragePermission = ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE); if (hasWriteExternalStoragePermission == PackageManager.PERMISSION_GRANTED) { selectPicture(); } else { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, requestCode); } break; } } private void selectPicture() { imageFile = MyHelper.createTempFile(imageFile); Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI); startActivityForResult(intent, RC_SELECT_PICTURE); } } Don’t waste time processing large images!

Next, create a new “MyHelper” class, where we’ll resize the user’s chosen image. By scaling the image down before passing it to ML Kit’s detectors, we can accelerate the image processing tasks.

Code

import android.app.Activity; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Environment; import android.provider.MediaStore; import android.provider.Settings; import android.support.v7.app.AlertDialog; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ProgressBar; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import static android.graphics.BitmapFactory.decodeFile; import static android.graphics.BitmapFactory.decodeStream; public class MyHelper { private static Dialog mDialog; public static String getPath(Context context, Uri uri) { String path = ""; String[] projection = {MediaStore.Images.Media.DATA}; Cursor cursor = context.getContentResolver().query(uri, projection, null, null, null); int column_index; if (cursor != null) { column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); cursor.moveToFirst(); path = cursor.getString(column_index); cursor.close(); } return path; } public static File createTempFile(File file) { File dir = new File(Environment.getExternalStorageDirectory().getPath() + "/com.example.mlkit"); dir.mkdirs(); } if (file == null) { file = new File(dir, "original.jpg"); } return file; } public static void showDialog(Context context) { mDialog = new Dialog(context); mDialog.addContentView( new ProgressBar(context), new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT) ); mDialog.setCancelable(false); if (!mDialog.isShowing()) { mDialog.show(); } } public static void dismissDialog() { if (mDialog != null && mDialog.isShowing()) { mDialog.dismiss(); } } public static void needPermission(final Activity activity, final int requestCode, int msg) { AlertDialog.Builder alert = new AlertDialog.Builder(activity); alert.setMessage(msg); @Override dialogInterface.dismiss(); Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS); intent.setData(Uri.parse("package:" + activity.getPackageName())); activity.startActivityForResult(intent, requestCode); } }); @Override dialogInterface.dismiss(); } }); alert.setCancelable(false); alert.show(); } public static Bitmap resizeImage(File imageFile, Context context, Uri uri, ImageView view) { BitmapFactory.Options options = new BitmapFactory.Options(); try { decodeStream(context.getContentResolver().openInputStream(uri), null, options); int photoW = options.outWidth; int photoH = options.outHeight; options.inSampleSize = Math.min(photoW / view.getWidth(), photoH / view.getHeight()); return compressImage(imageFile, BitmapFactory.decodeStream(context.getContentResolver().openInputStream(uri), null, options)); } catch (FileNotFoundException e) { e.printStackTrace(); return null; } } public static Bitmap resizeImage(File imageFile, String path, ImageView view) { BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; decodeFile(path, options); int photoW = options.outWidth; int photoH = options.outHeight; options.inJustDecodeBounds = false; options.inSampleSize = Math.min(photoW / view.getWidth(), photoH / view.getHeight()); return compressImage(imageFile, BitmapFactory.decodeFile(path, options)); } private static Bitmap compressImage(File imageFile, Bitmap bmp) { try { FileOutputStream fos = new FileOutputStream(imageFile); fos.close(); } catch (IOException e) { e.printStackTrace(); } return bmp; } } Displaying the user’s chosen image

Next, we need to grab the image the user selected from their gallery, and display it as part of our ImageView.

Code

import android.content.Intent; import android.graphics.Bitmap; import android.net.Uri; import android.os.Bundle; import android.view.View; import android.widget.ImageView; import android.widget.TextView; private Bitmap mBitmap; private ImageView mImageView; private TextView mTextView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mTextView = findViewById(R.id.textView); mImageView = findViewById(R.id.imageView); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == RESULT_OK) { switch (requestCode) { case RC_STORAGE_PERMS1: checkStoragePermission(requestCode); break; case RC_SELECT_PICTURE: Uri dataUri = data.getData(); String path = MyHelper.getPath(this, dataUri); if (path == null) { mBitmap = MyHelper.resizeImage(imageFile, this, dataUri, mImageView); } else { mBitmap = MyHelper.resizeImage(imageFile, path, mImageView); } if (mBitmap != null) { mTextView.setText(null); mImageView.setImageBitmap(mBitmap); } break; } } } @Override } } Teaching an app to label images on-device

We’ve laid the groundwork, so we’re ready to start labeling some images!

Customize the image labeler

While you could use ML Kit’s image labeler out of the box, you can also customize it by creating a FirebaseVisionLabelDetectorOptions object, and applying your own settings.

I’m going to create a FirebaseVisionLabelDetectorOptions object, and use it to tweak the confidence threshold. By default, ML Kit only returns labels with a confidence threshold of 0.5 or higher. I’m going to raise the bar, and enforce a confidence threshold of 0.7.

Code

FirebaseVisionLabelDetectorOptions options = new FirebaseVisionLabelDetectorOptions.Builder() .setConfidenceThreshold(0.7f) .build(); Create a FirebaseVisionImage object

ML Kit can only process images when they’re in the FirebaseVisionImage format, so our next task is converting the user’s chosen image into a FirebaseVisionImage object.

Since we’re working with Bitmaps, we need to call the fromBitmap() utility method of the FirebaseVisionImage class, and pass it our Bitmap:

Code

FirebaseVisionImage image = FirebaseVisionImage.fromBitmap(mBitmap); Instantiate the FirebaseVisionLabelDetector

ML Kit has different detector classes for each of its image recognition operations. Since we’re working with the Image Labeling API, we need to create an instance of FirebaseVisionLabelDetector.

If we were using the detector’s default settings, then we could instantiate the FirebaseVisionLabelDetector using getVisionLabelDetector(). However, since we’ve made some changes to the detector’s default settings, we instead need to pass the FirebaseVisionLabelDetectorOptions object during instantiation:

Code

FirebaseVisionLabelDetector detector = FirebaseVision.getInstance().getVisionLabelDetector(options); The detectInImage() method

Next, we need to pass the FirebaseVisionImage object to the FirebaseVisionLabelDetector’s detectInImage method, so it can scan and label the image’s content. We also need to register onSuccessListener and onFailureListener listeners, so we’re notified whenever results become available, and implement the related onSuccess and onFailure callbacks.

} } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { } }); } } }

Retrieving the labels and confidence scores

Assuming the image labeling operation is a success, an array of FirebaseVisionLabels will pass to our app’s OnSuccessListener. Each FirebaseVisionLabel object contains the label plus its associated confidence score, so the next step is retrieving this information and displaying it as part of our TextView:

Code

@Override for (FirebaseVisionLabel label : labels) { mTextView.append(label.getLabel() + "n"); mTextView.append(label.getConfidence() + "nn"); } }

At this point, your MainActivity should look something like this:

Code

import android.content.Intent; import android.graphics.Bitmap; import android.net.Uri; import android.os.Bundle; import android.support.annotation.NonNull; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.firebase.ml.vision.FirebaseVision; import com.google.firebase.ml.vision.label.FirebaseVisionLabel; import com.google.firebase.ml.vision.label.FirebaseVisionLabelDetector; import com.google.firebase.ml.vision.label.FirebaseVisionLabelDetectorOptions; import java.util.List; private Bitmap mBitmap; private ImageView mImageView; private TextView mTextView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mTextView = findViewById(R.id.textView); mImageView = findViewById(R.id.imageView); } @Override mTextView.setText(null); switch (view.getId()) { case R.id.btn_device: if (mBitmap != null) { FirebaseVisionLabelDetectorOptions options = new FirebaseVisionLabelDetectorOptions.Builder() .setConfidenceThreshold(0.7f) .build(); FirebaseVisionImage image = FirebaseVisionImage.fromBitmap(mBitmap); FirebaseVisionLabelDetector detector = FirebaseVision.getInstance().getVisionLabelDetector(options); @Override for (FirebaseVisionLabel label : labels) { mTextView.append(label.getLabel() + "n"); mTextView.append(label.getConfidence() + "nn"); } } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { mTextView.setText(e.getMessage()); } }); } } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == RESULT_OK) { switch (requestCode) { case RC_STORAGE_PERMS1: checkStoragePermission(requestCode); break; case RC_SELECT_PICTURE: Uri dataUri = data.getData(); String path = MyHelper.getPath(this, dataUri); if (path == null) { mBitmap = MyHelper.resizeImage(imageFile, this, dataUri, mImageView); } else { mBitmap = MyHelper.resizeImage(imageFile, path, mImageView); } if (mBitmap != null) { mTextView.setText(null); mImageView.setImageBitmap(mBitmap); } break; } } } } Analyze an image with ML Kit

At this point, our app can download ML Kit’s Image Labeling model, process an image on device, and then display the labels and corresponding confidence scores for that image. It’s time to put our application to the test:

Install this project on your Android device, or AVD.

Tap the action bar icon to launch your device’s Gallery.

Select the image that you want to process.

Give the “Device” button a tap.

Analyzing images in the cloud

Code

FirebaseVisionCloudDetectorOptions options = new FirebaseVisionCloudDetectorOptions.Builder() .setModelType(FirebaseVisionCloudDetectorOptions.LATEST_MODEL) .setMaxResults(5) .build();

Next, you need to run the image labeler by creating a FirebaseVisionImage object from the Bitmap, and passing it to the FirebaseCloudVisionLabelDetector’s detectInImage method:

Code

FirebaseVisionImage image = FirebaseVisionImage.fromBitmap(mBitmap);

Then we need to get an instance of FirebaseVisionCloudLabelDetector:

Code

FirebaseVisionCloudLabelDetector detector = FirebaseVision.getInstance().getVisionCloudLabelDetector(options);

Finally, we pass the image to the detectInImage method, and implement our onSuccess and onFailure listeners:

@Override } } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { } }); }

If the image labeling operation is a success, a list of FirebaseVisionCloudLabel objects will be passed to our app’s success listener. We can then retrieve each label and its accompanying confidence score, and display it as part of our TextView:

Code

@Override MyHelper.dismissDialog(); for (FirebaseVisionCloudLabel label : labels) { mTextView.append(label.getLabel() + ": " + label.getConfidence() + "nn"); mTextView.append(label.getEntityId() + "n"); } }

At this point, your MainActivity should look something like this:

Code

import android.content.Intent; import android.graphics.Bitmap; import android.net.Uri; import android.os.Bundle; import android.support.annotation.NonNull; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.firebase.ml.vision.FirebaseVision; import com.google.firebase.ml.vision.cloud.FirebaseVisionCloudDetectorOptions; import com.google.firebase.ml.vision.cloud.label.FirebaseVisionCloudLabel; import com.google.firebase.ml.vision.cloud.label.FirebaseVisionCloudLabelDetector; import com.google.firebase.ml.vision.label.FirebaseVisionLabel; import com.google.firebase.ml.vision.label.FirebaseVisionLabelDetector; import com.google.firebase.ml.vision.label.FirebaseVisionLabelDetectorOptions; import java.util.List; private Bitmap mBitmap; private ImageView mImageView; private TextView mTextView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mTextView = findViewById(R.id.textView); mImageView = findViewById(R.id.imageView); } @Override mTextView.setText(null); switch (view.getId()) { case R.id.btn_device: if (mBitmap != null) { FirebaseVisionLabelDetectorOptions options = new FirebaseVisionLabelDetectorOptions.Builder() .setConfidenceThreshold(0.7f) .build(); FirebaseVisionImage image = FirebaseVisionImage.fromBitmap(mBitmap); FirebaseVisionLabelDetector detector = FirebaseVision.getInstance().getVisionLabelDetector(options); @Override for (FirebaseVisionLabel label : labels) { mTextView.append(label.getLabel() + "n"); mTextView.append(label.getConfidence() + "nn"); } } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { mTextView.setText(e.getMessage()); } }); } break; case R.id.btn_cloud: if (mBitmap != null) { MyHelper.showDialog(this); FirebaseVisionCloudDetectorOptions options = new FirebaseVisionCloudDetectorOptions.Builder() .setModelType(FirebaseVisionCloudDetectorOptions.LATEST_MODEL) .setMaxResults(5) .build(); FirebaseVisionImage image = FirebaseVisionImage.fromBitmap(mBitmap); FirebaseVisionCloudLabelDetector detector = FirebaseVision.getInstance().getVisionCloudLabelDetector(options); @Override MyHelper.dismissDialog(); for (FirebaseVisionCloudLabel label : labels) { mTextView.append(label.getLabel() + ": " + label.getConfidence() + "nn"); mTextView.append(label.getEntityId() + "n"); } } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { MyHelper.dismissDialog(); mTextView.setText(e.getMessage()); } }); } break; } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == RESULT_OK) { switch (requestCode) { case RC_STORAGE_PERMS1: checkStoragePermission(requestCode); break; case RC_SELECT_PICTURE: Uri dataUri = data.getData(); String path = MyHelper.getPath(this, dataUri); if (path == null) { mBitmap = MyHelper.resizeImage(imageFile, this, dataUri, mImageView); } else { mBitmap = MyHelper.resizeImage(imageFile, path, mImageView); } if (mBitmap != null) { mTextView.setText(null); mImageView.setImageBitmap(mBitmap); } } } } } Activating Google’s cloud-based APIs

ML Kit’s cloud-based APIs are all premium services, so you’ll need to upgrade your Firebase project to a Blaze plan before your cloud-based code actually returns any image labels.

Although you’ll need to enter your payment details and commit to a pay-as-you-go Blaze plan, at the time of writing you can upgrade, experiment with the ML Kit features within the 1,000 free quota limit, and switch back to the free Spark plan without being charged. However, there’s no guarantee the terms and conditions won’t change at some point, so before upgrading your Firebase project always read all the available information, particularly the AI & Machine Learning Products and Firebase pricing pages.

If you’ve scoured the fine print, here’s how to upgrade to Firebase Blaze:

Head over to the Firebase Console.

A popup should now guide you through the payment process. Make sure you read all the information carefully, and you’re happy with the terms and conditions before you upgrade.

You can now enable ML Kit’s cloud-based APIs:

In the Firebase Console’s left-hand menu, select “ML Kit.”

Push the “Enable Cloud-based APIs” slider into the “On” position.

Testing your completed machine learning app

That’s it! Your app can now process images on-device and in the cloud. Here’s how to put this app to the test:

Install the updated project on your Android device, or AVD.

Make sure you have an active internet connection.

Choose an image from your device’s Gallery.

Give the “Cloud” button a tap.

Keep an eye on your spending

Since the cloud API is a pay-as-you-go service, you should monitor how your app uses it. The Google Cloud Platform has a dashboard where you can view the number of requests your application processes, so you don’t get hit by any unexpected bills!

You can also downgrade your project from Blaze back to the free Spark plan at any time:

Head over to the Firebase Console.

Select the free Spark plan.

You should receive an email confirming that your project has been downgraded successfully.

Wrapping up

You’ve now built your own machine learning-powered application, capable of recognizing entities in an image using both on-device and in-the-cloud machine learning models.

Have you used any of the ML Kit APIs we’ve covered on this site?

Update the detailed information about How To Compress An Image’S File Size Dramatically And Still Maintain Quality. on the Kientrucdochoi.com website. We hope the article's content will meet your needs, and we will regularly update the information to provide you with the fastest and most accurate information. Have a great day!