How can I make any type of image mode (landscape or portrait) fit into a parent control?

Donald Symmons 3,066 Reputation points
2022-12-16T11:45:44.673+00:00

I have a card control on my page, with image control inside of it. When I upload a portrait image or landscape image the display is not what I expected. The landscape image skips out from the card control, but the portrait image shows its fill width and height inside the card control. How can I make both image types (Landscape and portrait) to show inside the card and not skip over the card control?
Or is card control the right control to use in this kind of situation?
I just want it that regardless of image mode a user uploads, be it in landscape mode or portrait mode, they will sit inside their parent control. Kind of like a flexible container

<head runat="server">  
  
<link href="css/bootstrap.min.css" rel="stylesheet" media="all" />  
    <link href="css/bootstrap.css" rel="stylesheet" media="all" />  
    <title></title>  
    <style type="text/css">  
         #imgFileUpload {  
            cursor: pointer;  
            position: relative;  
            border-radius: 20px;  
        }  
          #parent {  
            position: relative;  
            width: auto;  
            height: auto;  
            font-size: 24px;  
            text-align: center;  
        }  
    </style>  
</head>  
<body>  
    <form id="form1" runat="server">  
        <div>  
            <br />  
            <div class="row col-sm-11" style="width: 100%; margin: 0 auto; padding: 6px;">  
                <div class="col-sm-6">  
                    <div class="card" style="width: 100%; border-radius: 3px;position: absolute;">  
                        <div class="card-body">  
                            <div id="parent" style="margin: 0 auto; margin-top: 0%; position: center;">  
                                <asp:FileUpload ID="fuUpload" runat="server" Style="display: none" />  
                                <asp:Image ID="imgFileUpload" ImageUrl="Test.png" runat="server" />  
                            </div>  
                        </div>  
                    </div>  
                </div>  
                <div cass="col-sm-6">  
                </div>  
            </div>              
        </div>  
    </form>  
     <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>  
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js" integrity="sha384-cs/chFZiN24E4KMATLdqdvsezGxaGsi4hLGOzlXwp5UZB1LY//20VyM2taTB4QvJ" crossorigin="anonymous"></script>  
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js" integrity="sha384-uefMccjFJAIv6A+rW+L4AHf99KvxDjWSu1z9VI8SKNVmz4sk7buKt/6v9KI65qnm" crossorigin="anonymous"></script>  
    <script src="https://cdnjs.cloudflare.com/ajax/libs/malihu-custom-scrollbar-plugin/3.1.5/jquery.mCustomScrollbar.concat.min.js"></script>  
    <script type="text/javascript">  
        $(function () {  
            var fileUpload = $("[id*=fuUpload]");  
            var img = $("[id*=imgFileUpload]");  
            img.click(function () { fileUpload.click(); });  
            fileUpload.change(function () {  
                var reader = new FileReader();  
                reader.onload = function (e) {  
                    $("[id*=imgFileUpload]").attr("src", e.target.result);  
                }  
                reader.readAsDataURL($(this)[0].files[0]);  
            });  
        });  
    </script>  
</body>  
Developer technologies | ASP.NET | Other
0 comments No comments
{count} votes

Accepted answer
  1. SurferOnWww 4,721 Reputation points
    2022-12-17T01:33:52.577+00:00

    How about using the HTML <canvas> element? You will be able to resize the image to the specified size and draw it on the canvas.

    Shown below is a sample code of ASP.NET Core MVC view.

    @{  
        ViewData["Title"] = "Canvas2";  
    }  
       
    <h1>Canvas2</h1>  
       
    <input type="file" id="file1" />  
    <input id="button1" type="button" value="Upload" style="display:none;" />  
    <br />  
    <div id="msg"></div>  
    <canvas id="mycanvas"></canvas>  
    <div id="result"></div>  
       
    @section Scripts {  
        <script type="text/javascript">  
        //<![CDATA[  
       
            const maxFileSize = 500000;  
            const allowedContentType = "image/jpeg";  
       
            // resize image less than the following size  
            const maxWidth = 500;  
            const maxHeight = 500;  
       
            let inputFile, uploadButton, msgDiv, myCanvas, resultDiv;  
       
            const CreateDataUrl = file => {  
                return new Promise(resolve => {  
                    const reader = new FileReader();  
                    reader.addEventListener('loadend',   
                                    e => resolve(e.target.result));  
                    reader.readAsDataURL(file);  
                });  
            };  
       
            const CreateImage = dataUrl => {  
                return new Promise(resolve => {  
                    const img = new Image();  
                    img.addEventListener('load',   
                                         e => resolve(e.target));  
                    img.src = dataUrl;  
                });  
            };  
       
            window.addEventListener('DOMContentLoaded', () => {  
       
                inputFile = document.getElementById("file1");  
                uploadButton = document.getElementById("button1");  
                msgDiv = document.getElementById("msg");  
                myCanvas = document.getElementById("mycanvas");  
                resultDiv = document.getElementById("result");  
       
                if (window.File && window.FileReader && window.FileList) {  
       
                    uploadButton.addEventListener('click', uploadImage);  
       
                    inputFile.addEventListener('change', async () => {  
                        resultDiv.innerText = "";  
       
                        if (ClientValidate(inputFile) == false) {  
                            uploadButton.style.display = "none";  
                            myCanvas.style.display = "none";  
                            return;  
                        }  
       
                        let dataUrl = await CreateDataUrl(inputFile.files[0]);  
       
                        let img = await CreateImage(dataUrl);  
       
                        // draw resized image on canvas  
                        DrawImageOnCanvas(img);  
                    });  
                }  
                else {  
                    inputFile.style.display = "none";  
                    myCanvas.style.display = "none";  
                    msgDiv.innerText = "File API not supported";  
                }  
            });  
       
            // helper method to validate the selected image file  
            function ClientValidate(fileUpload) {  
                msgDiv.innerText = "";  
       
                if (fileUpload.files[0] == null) {  
                    msgDiv.innerText = "file not selected";  
                    return false;  
                }  
       
                if (fileUpload.files[0].type != allowedContentType) {  
                    msgDiv.innerText = "file type is not " +  allowedContentType;  
                    return false;  
                }  
       
                if (fileUpload.files[0].size > maxFileSize) {  
                    msgDiv.innerText = "file size exceeds " + maxFileSize;  
                    return false;  
                }  
       
                return true;  
            }  
       
            // resize image to specified size and draw it on canvas  
            function DrawImageOnCanvas(image) {  
                // size of original image  
                const w = image.width;  
                const h = image.height;  
       
                let targetW, targetH;  
                const context = myCanvas.getContext('2d');  
       
                if (w <= maxWidth && h <= maxHeight) {  
                    myCanvas.setAttribute('width', w);  
                    myCanvas.setAttribute('height', h);  
                    context.drawImage(image, 0, 0);  
                }  
                else if (w < h) {  
                    targetH = maxHeight;  
                    targetW = Math.floor(w * targetH / h);  
                    myCanvas.setAttribute('width', targetW);  
                    myCanvas.setAttribute('height', targetH);  
                    context.drawImage(image, 0, 0, targetW, targetH);  
                }  
                else {  
                    targetW = maxWidth;  
                    targetH = Math.floor(h * targetW / w);  
                    myCanvas.setAttribute('width', targetW);  
                    myCanvas.setAttribute('height', targetH);  
                    context.drawImage(image, 0, 0, targetW, targetH);  
                }  
       
                uploadButton.style.display = "inline-block";  
                myCanvas.style.display = "block";  
            }  
       
            // upload image on canvas to server  
            async function uploadImage() {  
                const context = myCanvas.getContext('2d');  
                const dataUrl = context.canvas.toDataURL("image/jpeg");  
                const params = {  
                    method: "POST",  
                    body: '{"imgBase64":"' + dataUrl + '"}',  
                    headers: { 'Content-Type': 'application/json' }  
                }  
                const response = await fetch("/api/Canvas", params);  
                if (response.ok) {  
                    const message = await response.text();  
                    resultDiv.innerText = message  
                } else {  
                    resultDiv.innerText = "アップロード失敗";  
                }  
            }  
       
        //]]>  
        </script>  
    }  
    

    Result:

    271498-result.jpg


2 additional answers

Sort by: Most helpful
  1. Bruce (SqlWork.com) 78,006 Reputation points Volunteer Moderator
    2022-12-16T17:05:08.077+00:00

    the div hosting the image has size constraints, but the image does not. so if the image d bigger than the div, it will overflow. assuming the card only has a width constraint, make the image width constrained to the card.


  2. Donald Symmons 3,066 Reputation points
    2022-12-17T10:17:17.403+00:00

    I set the width attribute of the image control to 100%

     #image1 {   
     cursor: pointer;   
     position: relative;   
     border-radius: 20px;   
     width: 100%; }  
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.