Explore a sneak peek of images from my HTML CSS image gallery

I developed an application where users can take photos that are then uploaded to a server. Each image is assigned a unique number and displayed in a gallery. Users have the option to download individual images or all images in a .zip file.

Due to the potential for users to upload numerous images, I encountered performance issues with the gallery when it reached a certain size (e.g., 20 images). The webpage became slow and poorly optimized.

To address this issue, I implemented a method to resize the photos. However, this presents a challenge as users may want to download the original, full-size image rather than the resized version.

I attempted to modify my method to accommodate downloading larger images by sending a higher size parameter, but encountered difficulties making it work.

The resizing method code snippet:

private void ChangeImageSize(List<OrderViewModel> orderViewModels, int newSize)
        {
            try
            {
                foreach (var item in orderViewModels)
                {
                    var imageResult = Image.Load("wwwroot/" + item.getImages());

                    this.SaveImage(imageResult, "wwwroot/" + item.getImages(), newSize);
                }
            }
            catch (Exception ex)
            {
                ViewData["ERROR"] = ex.Message;
                throw new Exception(ex.Message);
            }

        }

        private void SaveImage(Image image, string name, int resizeWidth)
        {
            var width = image.Width;
            var height = image.Height;

            if (width > resizeWidth)
            {
                height = (int)((double)resizeWidth / width * height);
                width = resizeWidth;
            }

            picture
                .Mutate(i => i.Resize(new Size(width, height)));

            image.Metadata.ExifProfile = null;

            image.SaveAsJpeg(name, new JpegEncoder
            {
                Quality = 100
            });
        }

An example of how the method is used:

private List<OrderViewModel> ViewOrder(string identi)
         {
             List<OrderViewModel> OrderList;
             string query;

             try
             {
                 OrderList = new List<OrderViewModel>();
                 query = "SELECT DISTINCT p.Order, p.Delivery, p.Remit, e.Path, e.Date from Order p INNER JOIN Delivery e ON p.Delivery = e.Delivery WHERE p.Order = '" + identi + " ' GROUP BY p.Order";

                 OrderList = SelectMySqlConnection(query);

                 if (orderList.Count == 0 || orderList == null)
                 {
                     return OrderList;
                 }

                ChangeImageSize(orderList, 500);

                 return OrderList;
             }
             catch (Exception ex)
             {
                 ViewData["ERROR"] = ex.Message;
                 throw new Exception(ex.ToString());
             }
         }

Attempt at re-resizing images to increase size:

foreach (var list in orderList)
                     {
                         if(count == 0)
                         {
                             ChangeImageSize(orderList, 1000);
                             count = 1;
                         }
                         // imgAndroid\2022\09\06\images....
                         imageName = list.getImagePath().Split("/");
                         var file_name = imageName[5];
                         var array_fileBytes = System.IO.File.ReadAllBytes(@"wwwroot/" + list.getImages());
                         zip.AddEntry(file_name, file_arrayBytes);
                     }

I will use the tags C#, asp.net, html , and css as there might be different approaches for front-end and back-end aspects.

Answer №1

Solution 1:

If you're looking to efficiently manage photo uploads, one approach could be to save both the original and compressed versions of the images. Create two separate directories named "original" and "compressed" respectively. Display the compressed images in your gallery while providing a download link that references the corresponding original image.

Solution 2:

Another method is to dynamically compress photos as they are requested. Store the original uncompressed photos on your server and create a custom handler or page that fetches the original image, processes it by compressing or resizing it, and then displays the modified version. This process can be done in memory with binary writing the photostream, or saved to disk before being presented.

For instance:

While the following example uses asp.net web forms, a similar approach can be implemented

<img src="photocompressor.ashx?photo=somepath" />

In photocompressor.ashx

//Your code for loading, compressing, and resizing the image stored in "imgbytes"

Response.ContentType = "image/jpg";
Response.BinaryWrite(imgbytes);
Response.End();

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What's causing this javascript to malfunction on the browser?

I encountered a problem with the code in my .js file. Here is a snippet of the code: $.extend(KhanUtil, { // This function takes a number and returns its sign customSign: function(num){ num = parseFloat(num) if (num>=0){return 1} ...

I prefer not to receive the parent's opacity settings when styling a child element in CSS

Is there a way to prevent the child element from inheriting the opacity of the parent in CSS? I have a parent div and a child div inside it. I want to set the opacity for the parent div, but not have it affect the child div. Does anyone know how I can ac ...

Converting JSON into object representation with modified name field

I am facing a challenge with deserializing this JSON data: { "name": { "field": "kop", "field2": false } } The issue is that the key "Name" keeps changing. How can I handle this situation? For instance, i ...

JavaScript code for sorting a table based on a time interval

There is an index file with a flight schedule table. The table allows sorting by airline and departure time, as well as filtering by airline name. I'm trying to figure out how to add filtering by time range, specifically departing flights between 8 AM ...

Tips for ensuring the list stays perfectly centered within the navigation bar when placed among three images

I have my navigation bar set up with the logo on the far left and two flags for English and Italian on the far right. The issue I'm facing is that the UL element, being a block element, pushes the flags onto the next line. However, I want the UL to be ...

Is it possible for Firebug to display CSS comments? This feature would greatly assist in utilizing SASS

Can Firebug display CSS comments? I'm wondering if it can help with debugging when using line numbers from SASS. I haven't been able to find any information on this feature, so any help would be greatly appreciated. ...

The technique for converting a JSON format date string into a date format

Currently, I am fetching data from a database using AJAX and displaying it in HTML text boxes for updating purposes. Below is the Web Method code that successfully retrieves the data: [WebMethod] public static List<Employee> getEmployee() { var ...

Guide to modifying the attributes exclusively of the external borders in Bootstrap tables

Is there a way to customize only the outer border of a bootstrap 4 table by changing properties such as border-color, border-style, and border-radius? I attempted to do so, but it seems that the properties are being overridden. Here is my code: <!DOCT ...

Are there any known browser compatibility issues with using "./" (dot slash) before HTML files?

Within the realm of shells, using ./ to indicate the current directory is quite common and generally not perceived as risky when specifying a path. On the other hand, in HTML coding, it's typical to omit ./ and instead directly specify the file name. ...

Calling a SAP function module within Xamarin.Forms is achievable

Currently, I am facing a challenge as I am unable to use SAP .NET Connector (sapnco.dll) and haven't been able to find another suitable connector for Xamarin and SAP integration. My main concern is how to effectively call a SAP function from my Xamari ...

Is turning the Data Access Layer into a web service a viable option?

After spending considerable time on research, I have managed to develop a prototype ASP.NET web service as a Data Access Layer (DAL) for some ASP.NET 2.0 websites. Seeking advice from experienced developers who have successfully implemented DAL as a web se ...

Leveraging $implict for transferring several parameters

Need help with creating a recursive template that can accept multiple parameters: <ng-container *ngTemplateOutlet="testTemplate; context: {$implicit:jsonObj1}"> </ng-container> <ng-template #testTemplate let-Json1> </ng-template> ...

SignalR failing to send data to clients following a page refresh

After implementing SignalR to create a HUB where I can subscribe to stats and receive responses from the Server, everything seems to be working smoothly. Upon logging in for the first time, I am able to receive all the subscribed stats on the client side t ...

Adjust the column count in mat-grid-list upon the initial loading of the component

My goal is to implement a mat-grid-list of images with a dynamic number of columns based on the screen size. Everything works perfectly except for one small glitch – when the grid first loads, it defaults to 3 columns regardless of the screen size until ...

Sending Data from Model to Controller with Ajax in ASP.NET 5 / MVC 6

I'm encountering a problem in my ASP.NET 5 MVC 6 application when trying to use Ajax to post data to my controller. I have successfully done this in ASP.NET MVC 5, and even tested the exact same code in a new ASP.NET MVC 5 project where it worked perf ...

Preventing an object from exceeding the boundaries of its designated space

My DIV is filled with user-generated content, which sometimes begins with an item that has a margin-top that overflows the container, creating a gap between it and preceding elements. I've discovered that changing the display property to either inline ...

Having trouble with Firefox not recognizing the linear gradient color in my CSS3 code

I'm working on implementing a linear gradient background using CSS, but I'm facing an issue with Firefox not displaying it correctly. body { height: 100%; /*background-color: #F0F0F0;*/ background-repeat: repeat-x; /* Safari 4-5, Chrome 1-9 */ ...

Converting DateTime to Hex and reverting it back without using an Int64 conversion

Is there a way to directly convert DateTime to a Hex string, and vice versa? My current method of converting DateTime to a Hex string involves multiple conversions like Convert.ToInt64(dt.ToString("yyyyMMddhhmmss")).ToString("X2"), is there a more straigh ...

Differences Between TcpClient and Socket for Transmitting Large FilesWhen it

Currently, I am in the process of transferring a large file using TcpClient and NetworkStream class. However, I have encountered issues where bytes are being lost when using NetworkStream.Write and Read. I am unsure of how to ensure that TCP will stop read ...

Position a div at the center of the mouse cursor using this guide

Would appreciate guidance on my goal of placing a div in the center of the mouse cursor upon clicking a link. Here's what I have so far: <a id='btn' href='#' ><img src='test.png' /></a> I want the new ...