Web

Image Management in Web Development

Strategies and Practices

Posted by Enovace on March 1, 2024

Image optimization

Image optimization is an important part of website performance optimization, which involves a number of aspects, including reducing file size, choosing the right image format, implementing responsive images, and considering lazy loading or preloading of images.

1. Choosing the right image format

Image file size directly affects the loading speed of a web page, especially on mobile devices and low-speed networks. Image compression is the main means to reduce the image file size, which can be done by reducing the resolution of the image, adjusting the quality of the image, or removing the metadata in the image. There are many online tools and software that can help us compress images, such as TinyPNG, ImageOptim, and so on.

2. Choose the right image format

In web development, choosing the right image format can greatly affect the quality and file size of the image. For example, JPEG format is usually suitable for complex color-rich images, PNG format is suitable for images that require transparent backgrounds, GIF is suitable for small animations, while the new WebP and AVIF formats provide higher compression ratios while maintaining quality.

3. Implementing Responsive Images

Responsive images are images that are adapted to the screen size and resolution of the user’s device. This is mainly achieved through HTML5’s srcset and sizes attributes, and can also be achieved through CSS’s media queries. Responsive images not only provide a better user experience, but also improve page loading speed by avoiding loading oversized images unnecessarily.

4. Lazy loading and preloading of images

Lazy loading refers to starting to load an image when it enters or is about to enter the viewport, which avoids loading all the images as soon as the page is loaded, thus improving the loading speed of the page. Preloading, on the other hand, loads images ahead of time to reduce the amount of time users need to wait for images to load while browsing. Both ways have their pros and cons, and you should choose the appropriate loading strategy according to the specific situation.

Image storage

With the development of the website and the growth of the number of users, how to effectively store and manage image resources is a problem that must be faced. The choice of storage strategy needs to take into account the cost of storage, ease of use, scalability, data security and reliability and other factors.

1. Local Storage

Local storage is usually the most direct choice, i.e., to store images directly on their own server hard disk. The advantage of this approach is that it is simple and straightforward to operate, with no additional costs. However, as the number of images grows, its drawbacks become apparent: it requires a large amount of hard disk space, is complicated to back up and restore, and may lead to data loss when the server fails.

2. Cloud Storage

Cloud storage is another popular way to store images. By storing images on the servers of cloud service providers, it is easy to realize the expansion of storage space, and at the same time, cloud service providers usually provide data backup and recovery functions, which can guarantee the safety of data. Like Amazon S3, Google Cloud Storage, Alibaba OSS, etc. provide stable cloud storage services.

3. Content Distribution Network (CDN) Storage

Content Distribution Network (CDN) is a way to store data on multiple servers distributed in different geographic locations, and when a user requests data, it is fetched from the nearest server to increase the speed of data acquisition. The use of CDN for storing images is essential for large websites that have a large number of users and where the users are distributed across the globe.

4. Database Storage

Although less common, there are specific situations where we may choose to store images in a database, especially those that are small and closely associated with specific rows of data. For example, a user’s avatar image might be stored directly in the user’s database record. The advantage of this approach is that it can be easily associated with other data, but the disadvantage is that it increases the load on the database and does not easily handle large amounts of image data.

Image distribution

Image distribution mainly refers to how to efficiently send images from the server to the user’s device. The efficiency of image distribution directly affects the loading speed of images, which in turn affects the user experience.

1. Using HTTP/2

HTTP/2 is the latest version of the HTTP protocol, which has many performance optimizations compared to HTTP/1.x. HTTP/2 supports multiplexing, which allows multiple requests or responses to be transmitted in parallel over a single TCP connection, which greatly reduces the time it takes for images to load. Also, HTTP/2 supports server push, where the server can actively push resources to the client without the client having to explicitly request them.

2. Using a CDN

As mentioned above, a CDN (Content Delivery Network) is a way of storing data on multiple servers distributed in different geographical locations. When a user requests data, it is fetched from the nearest server, which not only improves the speed of data fetching, but also reduces the pressure on the original server.

3. Using Image Distribution Service

In addition to the general optimization methods mentioned above, there are also some services dedicated to image distribution, such as ImageKit, Cloudflare and so on. These services provide a full set of image processing and distribution functions, such as image format conversion, compression, cropping, and CDN distribution.

4. Pre-caching

Pre-caching is a method of downloading images to the user’s device before they are needed. In this way, when users need to display an image, they can get it directly from the local cache without downloading it from the server. This approach is suitable for those scenarios where the user needs to access frequently and the image does not change often.

Image loading strategy

Image loading strategy is an important factor that affects web performance and user experience. The right loading strategy can significantly improve the loading speed of web pages and reduce the waiting time of users.

1. Lazy Loading

Lazy loading is a method that starts loading images only when they enter or are about to enter the viewport. This method prevents all images from being loaded as soon as the page is loaded, significantly improving the initial loading speed of the page. For scenarios with a lot of image resources, especially long list pages, using lazy loading of images is a very effective strategy.

In HTML, lazy loading of images can be enabled via the loading=”lazy” attribute. For more complex scenarios, it may be necessary to use JavaScript (e.g. the Intersection Observer API).

2. Preloading

Contrary to lazy loading, preloading is a way to start loading images before the user needs them. This approach reduces the delay caused by waiting for an image to load while the user is browsing a web page.

In HTML, images can be preloaded via the tag. Note that excessive preloading may waste bandwidth and may affect the loading of other important resources, so it needs to be used with caution.

3. Adaptive Loading

Adaptive loading is a method of choosing an image loading strategy that adapts to the user’s device and network environment. For example, for mobile devices and slow networks, small-sized and low-quality images may be prioritized; for widescreen devices and fast networks, high-quality images may be chosen to be loaded. When implementing adaptive loading, it may be necessary for the server to support dynamic processing of images (e.g., resizing and quality adjustment), as well as the use of some HTML and CSS features (e.g., srcset and media attributes).

Image Management in Practice: Using Cloudinary

Cloudinary is a cloud-based image and video management service that provides a complete set of solutions especially suited for web applications that need to process and serve large numbers of images. To use Cloudinary in your Spring Boot application, you need to follow these steps:

1. Register and set up a Cloudinary account

First, you need to visit the Cloudinary website to register an account. After registering and logging in, you will see your Cloudinary cloud name, API Key, and API Secret in the control panel.This information will be used in subsequent steps.

2. Adding the Cloudinary Java SDK

You then need to add the Cloudinary Java SDK to your Spring Boot project. add the following dependency to your pom.xml file:

1
2
3
4
5
<dependency>
	<groupId>com.cloudinary</groupId>
	<artifactId>cloudinary-http44</artifactId>
	<version>1.27.1</version>
</dependency>

3. Creating a Cloudinary Configuration

Next, you need to create a Cloudinary configuration class in your project. This class will use the cloud name, API Key, and API Secret that you found in the Cloudinary control panel:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@Configuration
public class CloudinaryConfig {
    @Value("${cloudinary.cloud_name}")
    private String cloudName;

    @Value("${cloudinary.api_key}")
    private String apiKey;

    @Value("${cloudinary.api_secret}")
    private String apiSecret;

    @Bean
    public Cloudinary cloudinary() {
      return new Cloudinary(ObjectUtils.asMap(
          "cloud_name", cloudName,
          "api_key", apiKey,
          "api_secret", apiSecret));
    }
}

In this configuration class, we created a Cloudinary bean and initialized it with the information we found in the Cloudinary control panel.

Note: For security reasons, you should store your Cloudinary cloud name, API Key, and API Secret in a secure place rather than hard-coding them directly into the code. In this example, we have used Spring’s @Value annotation to get these values from the environment variable. 5.4 Using Cloudinary With this configuration, you can now use Cloudinary in your Spring Boot application. You can use Cloudinary objects for uploading, downloading, deleting, converting, etc. images.For example, here is an example of uploading an image

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
@Service
public class ImageService {
  private final Cloudinary cloudinary;

  public ImageService(Cloudinary cloudinary) {
    this.cloudinary = cloudinary;
  }

  public String uploadImage(MultipartFile file) throws IOException {
    File uploadedFile = convertMultiPartToFile(file);
    Map result = cloudinary.uploader().upload(uploadedFile, ObjectUtils.emptyMap());
    uploadedFile.delete();
    return (String) result.get("url");
  }

  private File convertMultiPartToFile(MultipartFile file) throws IOException {
    File convFile = new File(file

.getOriginalFilename());
    FileOutputStream fos = new FileOutputStream(convFile);
    fos.write(file.getBytes());
    fos.close();
    return convFile;
  }
}

In this example, we first convert MultipartFile to File, then upload the file using Cloudinary’s uploader method, and finally return the URL of the image.Note that the uploader method returns a Map with several fields (such as the image URL, information about the width and height of the image, etc.), which you can use as needed. fields as needed.

Cloudinary provides a powerful set of features including, but not limited to, storing and managing images, performing format conversions and optimizations, and even performing image content recognition and tagging. All of these features can be operated through a clean API, which will greatly simplify your image management efforts.

In addition, Cloudinary offers some other useful features such as lazy loading of images, adaptive image formats and quality, and image analytics. All these features can help you better manage and optimize your image resources.