Resize ảnh với HTML5 FileReader

Khi lập trình web, các vấn đề liên quan đến hình ảnh được sử dụng thường xuyên, ví dụ upload hình ảnh sản phẩm, banner, logo….

Từ đây nảy sinh vài vấn đề như: muốn thấy hình ảnh đại diện ngay khi chọn file. Resize hình ảnh để tiết kiệm dung lượng…. Trước khi HTML5 ra đời, chúng ta thường hay giải quyết mọi thứ trên server, tức là upload ảnh lên server, sau đó xử lý. VD: dùng ajax để upload ảnh lên server, sau đó trả về ảnh đại diện…. Điều này dẫn đến tốn thời gian xử lý cho máy chủ, hoặc file lớn, mạng chậm thì user phải chờ đợi rất lâu.

Thật may mắn khi HTML5 ra đời, nó giúp chúng ta cả 2 việc trên luôn. Đó là preview (xem trước) hình ảnh ngay khi vừa chọn xong, đồng thời resize ảnh luôn ngay trên trình duyệt. Sau đó chúng ta chỉ việc upload mã base64 này lên server, và convert lại thành hình ảnh là xong, hoặc lưu luôn base64 vào database cũng ok.

HTML sử dụng API FileReader, nó có thể đọc file ảnh, file txt, khá là thú vị.

Code chọn ảnh xong hiển thị ảnh đại diện

<input id="imageFile" name="imageFile" type="file" class="imageFile"  accept="image/*"   /> 
<br/>
<img src="" id="preview"  >

Code javascript

$(document).ready(function() {

    $('#imageFile').change(function(evt) {

        var files = evt.target.files;
        var file = files[0];

        if (file) {
            var reader = new FileReader();
            reader.onload = function(e) {
                document.getElementById('preview').src = e.target.result;
            };
            reader.readAsDataURL(file);
        }
    });
});

Các bạn chú ý, có sử dụng jQuery

Code resize hình ảnh

<input id="imageFile" name="imageFile" type="file" class="imageFile"  accept="image/*"   /> 
<input type="button" value="Resize Image"  onclick="ResizeImage()"/> 
<br/>
<img src="" id="preview"  >
<img src="" id="output">

Code javascript

function ResizeImage() {
    if (window.File && window.FileReader && window.FileList && window.Blob) {
        var filesToUploads = document.getElementById('imageFile').files;
        var file = filesToUploads[0];
        if (file) {

            var reader = new FileReader();
            // Set the image once loaded into file reader
            reader.onload = function(e) {

                var img = document.createElement("img");
                img.src = e.target.result;

                var canvas = document.createElement("canvas");
                var ctx = canvas.getContext("2d");
                ctx.drawImage(img, 0, 0);

                var MAX_WIDTH = 400;
                var MAX_HEIGHT = 400;
                var width = img.width;
                var height = img.height;

                if (width > height) {
                    if (width > MAX_WIDTH) {
                        height *= MAX_WIDTH / width;
                        width = MAX_WIDTH;
                    }
                } else {
                    if (height > MAX_HEIGHT) {
                        width *= MAX_HEIGHT / height;
                        height = MAX_HEIGHT;
                    }
                }
                canvas.width = width;
                canvas.height = height;
                var ctx = canvas.getContext("2d");
                ctx.drawImage(img, 0, 0, width, height);

                dataurl = canvas.toDataURL(file.type);
                document.getElementById('output').src = dataurl;
            }
            reader.readAsDataURL(file);

        }

    } else {
        alert('The File APIs are not fully supported in this browser.');
    }
}

See the Pen Resize Image with HTML5 File Reader by tuanitpro (@tuanitpro) on CodePen.


Chúc các bạn thành công.

SQL Server Date Formats

One of the most frequently asked questions in SQL Server forums is how to format a datetime value or column into a specific date format.  Here’s a summary of the different date formats that come standard in SQL Server as part of the CONVERT function.  Following the standard date formats are some extended date formats that are often asked by SQL Server developers.

It is worth to note that the output of these date formats are of VARCHAR data types already and not of DATETIME data type.  With this in mind, any date comparisons performed after the datetime value has been formatted are using the VARCHAR value of the date and time and not its original DATETIME value.

Standard Date Formats
Date FormatStandardSQL StatementSample Output
Mon DD YYYY 1
HH:MIAM (or PM)
DefaultSELECT CONVERT(VARCHAR(20), GETDATE(), 100)Jan 1 2005 1:29PM 1
MM/DD/YYUSASELECT CONVERT(VARCHAR(8), GETDATE(), 1) AS [MM/DD/YY]11/23/98
MM/DD/YYYYUSASELECT CONVERT(VARCHAR(10), GETDATE(), 101) AS [MM/DD/YYYY]11/23/1998
YY.MM.DDANSISELECT CONVERT(VARCHAR(8), GETDATE(), 2) AS [YY.MM.DD]72.01.01
YYYY.MM.DDANSISELECT CONVERT(VARCHAR(10), GETDATE(), 102) AS [YYYY.MM.DD]1972.01.01
DD/MM/YYBritish/FrenchSELECT CONVERT(VARCHAR(8), GETDATE(), 3) AS [DD/MM/YY]19/02/72
DD/MM/YYYYBritish/FrenchSELECT CONVERT(VARCHAR(10), GETDATE(), 103) AS [DD/MM/YYYY]19/02/1972
DD.MM.YYGermanSELECT CONVERT(VARCHAR(8), GETDATE(), 4) AS [DD.MM.YY]25.12.05
DD.MM.YYYYGermanSELECT CONVERT(VARCHAR(10), GETDATE(), 104) AS [DD.MM.YYYY]25.12.2005
DD-MM-YYItalianSELECT CONVERT(VARCHAR(8), GETDATE(), 5) AS [DD-MM-YY]24-01-98
DD-MM-YYYYItalianSELECT CONVERT(VARCHAR(10), GETDATE(), 105) AS [DD-MM-YYYY]24-01-1998
DD Mon YY 1SELECT CONVERT(VARCHAR(9), GETDATE(), 6) AS [DD MON YY]04 Jul 06 1
DD Mon YYYY 1SELECT CONVERT(VARCHAR(11), GETDATE(), 106) AS [DD MON YYYY]04 Jul 2006 1
Mon DD, YY 1SELECT CONVERT(VARCHAR(10), GETDATE(), 7) AS [Mon DD, YY]Jan 24, 98 1
Mon DD, YYYY 1SELECT CONVERT(VARCHAR(12), GETDATE(), 107) AS [Mon DD, YYYY]Jan 24, 1998 1
HH:MM:SSSELECT CONVERT(VARCHAR(8), GETDATE(), 108)03:24:53
Mon DD YYYY HH:MI:SS:MMMAM (or PM) 1Default +
milliseconds
SELECT CONVERT(VARCHAR(26), GETDATE(), 109)Apr 28 2006 12:32:29:253PM 1
MM-DD-YYUSASELECT CONVERT(VARCHAR(8), GETDATE(), 10) AS [MM-DD-YY]01-01-06
MM-DD-YYYYUSASELECT CONVERT(VARCHAR(10), GETDATE(), 110) AS [MM-DD-YYYY]01-01-2006
YY/MM/DDSELECT CONVERT(VARCHAR(8), GETDATE(), 11) AS [YY/MM/DD]98/11/23
YYYY/MM/DDSELECT CONVERT(VARCHAR(10), GETDATE(), 111) AS [YYYY/MM/DD]1998/11/23
YYMMDDISOSELECT CONVERT(VARCHAR(6), GETDATE(), 12) AS [YYMMDD]980124
YYYYMMDDISOSELECT CONVERT(VARCHAR(8), GETDATE(), 112) AS [YYYYMMDD]19980124
DD Mon YYYY HH:MM:SS:MMM(24h) 1Europe default + millisecondsSELECT CONVERT(VARCHAR(24), GETDATE(), 113)28 Apr 2006 00:34:55:190 1
HH:MI:SS:MMM(24H)SELECT CONVERT(VARCHAR(12), GETDATE(), 114) AS [HH:MI:SS:MMM(24H)]11:34:23:013
YYYY-MM-DD HH:MI:SS(24h)ODBC CanonicalSELECT CONVERT(VARCHAR(19), GETDATE(), 120)1972-01-01 13:42:24
YYYY-MM-DD HH:MI:SS.MMM(24h)ODBC Canonical
(with milliseconds)
SELECT CONVERT(VARCHAR(23), GETDATE(), 121)1972-02-19 06:35:24.489
YYYY-MM-DDTHH:MM:SS:MMMISO8601SELECT CONVERT(VARCHAR(23), GETDATE(), 126)1998-11-23T11:25:43:250
DD Mon YYYY HH:MI:SS:MMMAM 1KuwaitiSELECT CONVERT(VARCHAR(26), GETDATE(), 130)28 Apr 2006 12:39:32:429AM 1
DD/MM/YYYY HH:MI:SS:MMMAMKuwaitiSELECT CONVERT(VARCHAR(25), GETDATE(), 131)28/04/2006 12:39:32:429AM
Here are some more date formats that does not come standard in SQL Server as part of the CONVERT function.

Extended Date Formats
Date FormatSQL StatementSample Output
YY-MM-DD
SELECT SUBSTRING(CONVERT(VARCHAR(10), GETDATE(), 120), 3, 8) AS [YY-MM-DD]
SELECT REPLACE(CONVERT(VARCHAR(8), GETDATE(), 11), ‘/’, ‘-‘) AS [YY-MM-DD]
99-01-24
YYYY-MM-DD
SELECT CONVERT(VARCHAR(10), GETDATE(), 120) AS [YYYY-MM-DD]
SELECT REPLACE(CONVERT(VARCHAR(10), GETDATE(), 111), ‘/’, ‘-‘) AS [YYYY-MM-DD]
1999-01-24
MM/YYSELECT RIGHT(CONVERT(VARCHAR(8), GETDATE(), 3), 5) AS [MM/YY] SELECT SUBSTRING(CONVERT(VARCHAR(8), GETDATE(), 3), 4, 5) AS [MM/YY]08/99
MM/YYYYSELECT RIGHT(CONVERT(VARCHAR(10), GETDATE(), 103), 7) AS [MM/YYYY]12/2005
YY/MMSELECT CONVERT(VARCHAR(5), GETDATE(), 11) AS [YY/MM]99/08
YYYY/MMSELECT CONVERT(VARCHAR(7), GETDATE(), 111) AS [YYYY/MM]2005/12
Month DD, YYYY 1SELECT DATENAME(MM, GETDATE()) + RIGHT(CONVERT(VARCHAR(12), GETDATE(), 107), 9) AS [Month DD, YYYY]July 04, 2006 1
Mon YYYY 1SELECT SUBSTRING(CONVERT(VARCHAR(11), GETDATE(), 113), 4, 8) AS [Mon YYYY]Apr 2006 1
Month YYYY 1SELECT DATENAME(MM, GETDATE()) + ‘ ‘ + CAST(YEAR(GETDATE()) AS VARCHAR(4)) AS [Month YYYY]February 2006 1
DD Month 1SELECT CAST(DAY(GETDATE()) AS VARCHAR(2)) + ‘ ‘ + DATENAME(MM, GETDATE()) AS [DD Month]11 September 1
Month DD 1SELECT DATENAME(MM, GETDATE()) + ‘ ‘ + CAST(DAY(GETDATE()) AS VARCHAR(2)) AS [Month DD]September 11 1
DD Month YY 1SELECT CAST(DAY(GETDATE()) AS VARCHAR(2)) + ‘ ‘ + DATENAME(MM, GETDATE()) + ‘ ‘ + RIGHT(CAST(YEAR(GETDATE()) AS VARCHAR(4)), 2) AS [DD Month YY]19 February 72 1
DD Month YYYY 1SELECT CAST(DAY(GETDATE()) AS VARCHAR(2)) + ‘ ‘ + DATENAME(MM, GETDATE()) + ‘ ‘ + CAST(YEAR(GETDATE()) AS VARCHAR(4)) AS [DD Month YYYY]11 September 2002 1
MM-YYSELECT RIGHT(CONVERT(VARCHAR(8), GETDATE(), 5), 5) AS [MM-YY] SELECT SUBSTRING(CONVERT(VARCHAR(8), GETDATE(), 5), 4, 5) AS [MM-YY]12/92
MM-YYYYSELECT RIGHT(CONVERT(VARCHAR(10), GETDATE(), 105), 7) AS [MM-YYYY]05-2006
YY-MMSELECT RIGHT(CONVERT(VARCHAR(7), GETDATE(), 120), 5) AS [YY-MM] SELECT SUBSTRING(CONVERT(VARCHAR(10), GETDATE(), 120), 3, 5) AS [YY-MM]92/12
YYYY-MMSELECT CONVERT(VARCHAR(7), GETDATE(), 120) AS [YYYY-MM]2006-05
MMDDYYSELECT REPLACE(CONVERT(VARCHAR(10), GETDATE(), 1), ‘/’, ”) AS [MMDDYY]122506
MMDDYYYYSELECT REPLACE(CONVERT(VARCHAR(10), GETDATE(), 101), ‘/’, ”) AS [MMDDYYYY]12252006
DDMMYYSELECT REPLACE(CONVERT(VARCHAR(10), GETDATE(), 3), ‘/’, ”) AS [DDMMYY]240702
DDMMYYYYSELECT REPLACE(CONVERT(VARCHAR(10), GETDATE(), 103), ‘/’, ”) AS [DDMMYYYY]24072002
Mon-YY 1SELECT REPLACE(RIGHT(CONVERT(VARCHAR(9), GETDATE(), 6), 6), ‘ ‘, ‘-‘) AS [Mon-YY]Sep-02 1
Mon-YYYY 1SELECT REPLACE(RIGHT(CONVERT(VARCHAR(11), GETDATE(), 106), 8), ‘ ‘, ‘-‘) AS [Mon-YYYY]Sep-2002 1
DD-Mon-YY 1SELECT REPLACE(CONVERT(VARCHAR(9), GETDATE(), 6), ‘ ‘, ‘-‘) AS [DD-Mon-YY]25-Dec-05 1
DD-Mon-YYYY 1SELECT REPLACE(CONVERT(VARCHAR(11), GETDATE(), 106), ‘ ‘, ‘-‘) AS [DD-Mon-YYYY]25-Dec-2005 1

1 To make the month name in upper case, simply use the UPPER string function.

Convert Image to Base64 String and Base64 String to Image

This article will help you to learn how we can convert an image into a base64 string and base64 string back to image.

Image to Base64 String

public string ImageToBase64(Image image, System.Drawing.Imaging.ImageFormat format)
{
  using (MemoryStream ms = new MemoryStream())
  {
    // Convert Image to byte[]
    image.Save(ms, format);
    byte[] imageBytes = ms.ToArray();

    // Convert byte[] to Base64 String
    string base64String = Convert.ToBase64String(imageBytes);
    return base64String;
  }
}

Base64 String to Image

public Image Base64ToImage(string base64String)
{
  // Convert Base64 String to byte[]
  byte[] imageBytes = Convert.FromBase64String(base64String);
  MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);

  // Convert byte[] to Image
  ms.Write(imageBytes, 0, imageBytes.Length);
  Image image = Image.FromStream(ms, true);
  return image;
}

Coding in real world

 


Result

Download: https://github.com/tuanitpro/base64toimage

Online test: http://codebeautify.org/base64-to-image-converter

Happy coding 🙂

CSDL tên Quốc gia, tỉnh thành phố thị xã quận huyện, xã phường Việt Nam

  • Thông tin 245quốc gia trên thế giới
  • Thông tin 64 tỉnh thành  phố Việt Nam
  • Thông tin 697 quận huyện / thị xã
  • Thông tin 11110 xã phường

Nguồn tài liệu tham khảo: cổng thông tin điện tử các tỉnh thành, quận huyện, từ điển bách khoa toàn thư điện tử Wikipedia.
Định dạng dữ liệu: bảng cơ sở dữ liệu SQL
Mục đích: chia sẻ giúp các bạn webmaster đang muốn lấy một nguồn thông tin chuẩn mực về tên các đơn vị hành chính cho các dự án website, cổng thông tin điện tử ….

Download

 

Chúc các bạn thành công

Bootstrap modal not working with Kendo DropdownList

When using bootstrap modal with Kendo Dropdownlist, it not working. DropdownList auto Close. How to fix it

;//
// Popup extension.
// Sets up kendo popups (used in all sorts of widgets) to check if the widget
// is being included in a bootstrap modal. If so, the popup should append to
// the modal instead of the page body.
//
// For the most part, popups work fine without this. However, DropdownList with
// a filter option does not. This is because the filter attempts to focus on
// filter input, which is outside the modal By default, Bootstrap modal will
// block this. It has an option to allow, but then it must be remembered to add
// everywhere.
//
// This allows filtered dropdownlists to 'just work'.
//
// http://www.telerik.com/forums/dropdownlist-closes-when-setting-filter-option
//
// See for alternate solutions:
// http://www.telerik.com/forums/dropdownlist-with-server-filtering-on-bootstrap-modal
// http://stackoverflow.com/a/28471072/246561
//
(function ($, kendo) {

    var
        _init = kendo.ui.Popup.fn.init;

    var Popup = kendo.ui.Popup.extend({
        init: function (element, options) {
            // Only set appendTo if nothing was manually set in the options.
            if (options.appendTo === undefined) {
                // Find the nearest parent bootstrap modal, if any.
                var parentModal = $(options.anchor).closest('.modal');

                // Found one!
                if (parentModal.length > 0) {
                    options.appendTo = parentModal[0];
                }
            }

            // Call the base constructor.
            _init.call(this, element, options);
        }
    });

    kendo.ui.plugin(Popup);
}(window.kendo.jQuery, window.kendo));

 

Reverse opposing colors C#, Java

I have a user setup where they can choose the colors of the alerts. the Alert is the background color on a text or button. But the problem comes in that if they select a dark blue and we have black letters the contrast isnt enough and you cannot read it.

I have tried to make a function to get the reverse opposing color but havent got too far. Is there such a function?

—————-

I found that the best solution for me is to convert the RGB values into YIQ values. As we are only interested in the brightness value (represented by Y), there is one single calculation to be done: Y = (299*R + 587*G + 114*B)/1000. The Java code for that would look like this:

public static Color getContrastColor(Color color) {
  double y = (299 * color.getRed() + 587 * color.getGreen() + 114 * color.getBlue()) / 1000;
  return y >= 128 ? Color.black : Color.white;
}

Code C#

public static Color GetContrastColor(Color color)
        {
            double y = (double)(299 * color.R + 587 * color.G + 114 * color.B) / 1000;
            return y >= 128 ? Color.Black : Color.White;
        }

How to use

System.Drawing.Color col = System.Drawing.ColorTranslator.FromHtml("#3399cc");
var c = GetContrastColor(col);
 return "#" + c.R.ToString("X2") + c.G.ToString("X2") + c.B.ToString("X2");

 

T SQL Query Ultilities

— Find all Column not in Table

select name from sys.tables
where name not in
(
SELECT t.name 
FROM sys.columns c
    JOIN sys.tables t ON c.object_id = t.object_id
WHERE c.name LIKE 'IsDeleted'
)

— Deleting all duplicate rows but keeping one [duplicate]

WITH cte AS (
  SELECT FirstName, 
     row_number() OVER(PARTITION BY FirstName ORDER BY FirstName) AS [rn]
  FROM Client
)
DELETE cte WHERE [rn] > 1

— Adding a column to all user tables in T-SQL

exec sp_msforeachtable 'alter table ? add IsDeleted bit not null default 0';

--- Adding a column to all user table if not exists
EXEC sp_msforeachtable '
if not exists (select name from sys.tables
where name not in(SELECT t.name FROM sys.columns c
				JOIN sys.tables t ON c.object_id = t.object_id
				WHERE c.name LIKE ''IsDeleted'')
) 
begin
    ALTER TABLE ? ADD IsDeleted bit NOT NULL DEFAULT 0;
end';

 

Đọc toàn bộ dữ liệu trong Google Apps script

Hướng dẫn sau giúp bạn đọc toàn bộ dữ liệu trong 1 file google sheet, bằng ngôn ngữ Google Apps script. Sau đó chưa chúng vào một mảng để sử dụng cho mục đích khác.  Trong ví dụ chỉ đọc những ô có chứa dữ liệu.

function getSupplierData(){  
                
      var codeApp = SpreadsheetApp.openById(googleSheetId);
      var sheet = codeApp.getSheetByName(sheetName);       
      var lastColumn = sheet.getLastColumn();
      var lastRow = sheet.getLastRow();
     
      var range = sheet.getRange(rowStart,1,lastRow,lastColumn);
      var data = range.getValues();
          
      var rows=[];
      for(var i in data){
          for(var j = 0; j<lastColumn; j++){
            if(data[i][j] !=='') {
               var item = {name: data[i][j]};         
               rows.push(item);
             }
         }        
      }
      Logger.log(rows);
     return rows;
}