Upload Image Core .net ,JS ,ImageWaterMark, And Show Image
==============
index
===============
<div>
<img id="user_img" height="100" width="90" style="border:solid" />
</div>
<input type="file" id="portrait-image1" onchange="show(this)" />
<button type="button" onclick="uploadContentsTest()">upload test</button>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@10.16.4/dist/sweetalert2.all.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/jquery/latest/jquery.min.js"></script>
<script type="text/javascript">
function show(input) {
if (input.files && input.files[0]) {
var filerdr = new FileReader();
filerdr.onload = function (e) {
$('#user_img').attr('src', e.target.result);
}
filerdr.readAsDataURL(input.files[0]);
}
}
</script>
<script>
function uploadContentsTest() {
var url = '/Home/uploadContent';
var data = new FormData();
var files = $("#portrait-image1").get(0).files;
if (files.length > 0) {
data.append("HelpSectionImages", files[0]);
}
$.ajax({
type: 'POST',
url: url,
data: data,
cache: false,
contentType: false,
processData: false,
success: function (response) {
if (response.status === 0) {
let contentType = $('#content-type').val();
let eventId = $('#event-id').val();
if (contentType == "showcase" && eventId > 0) {
Swal.fire({
title: 'This Is Title',
text: "This is Text",
icon: "success"
}).then((result) => {
location.href = `/upload-content/${eventId}`;
});
return;
}
Swal.fire({
title: 'This Is Titile',
text: "Your content has been uploaded. You will receive a notification email when it's approved.",
icon: "success"
}).then(() => {
location.href = '@Url.Action("MyProfile", "Account")';
})
return;
}
Swal.fire({
title: 'This Is Title',
text: 'This Is Text',
icon: 'error'
});
},
error: function (response) {
Swal.fire({
title: 'This Is Title',
text: 'This Is Text',
icon: 'error'
});
}
});
}
</script>
============================
HomeController
============================
private IConfiguration _config;
public async Task<IActionResult> uploadContent()
{
//todo: content-id should be the parameter for this function.
try
{
int contentType = 5;
//var content = { id:};
var content = new { Id = 15 };
/// string title = Request.Form["title"];
/// int categoryId = int.Parse(Request.Form["category"]);
/// List<string> tagList = new List<string>();
int eventId = 0;
/// bool success = int.TryParse(Request.Form["event_id"], out eventId);
for (int i = 0; i < Request.Form.Files.Count; i++)
{
//save original files
// string filename = SaveFile(Request.Form.Files[i], contentType);
string thumbnail = SaveThumbnail(Request.Form.Files[i], contentType);
//await _repository.AddContentItem(content.Id, thumbnail, contentType, 0);
}
return Content("Ok");
}
catch (Exception e)
{
throw e;
}
}
//using six labor in most of component
private string SaveThumbnail(IFormFile input, int contentType)
{
string extension = input.FileName;
const string chars = "abcdefghijklmnopqrstuvwxyz1234567890";
int length = 32;
var random = new Random();
string randomName =
new string(Enumerable.Repeat(chars, length).Select(s => s[random.Next(s.Length)]).ToArray());
string fileName = $"{randomName}{extension}";
string path = $"D:/showtime/public/images/wm/{fileName}";//$"{directory}\\{fileName}";
string pathClear = $"D:/showtime/public/images/{fileName}";//$"{directoryClear}\\{fileName}";
try
{
using (var img = Image.Load(input.OpenReadStream()))
{
Rectangle? crop = null; // new Rectangle(0, 0, 0, 0);
if (img.Width > img.Height) // wide image
{
if ((float)img.Width / img.Height > 16f / 9)
{
int x = (int)((img.Width - 16f / 9 * img.Height) / 2);
int y = 0;
crop = new Rectangle(
x, y, (int)(16f / 9 * img.Height), img.Height);
}
else if ((float)img.Width / img.Height < 16f / 9)
{
int x = 0;
int y = (int)((img.Height - 9f / 16 * img.Width) / 2);
crop = new Rectangle(
x, y, img.Width, (int)(9f / 16 * img.Width));
}
}
else
{
//tall/square image
if ((float)img.Width / img.Height > 9f / 16)
{
int x = (int)((img.Width - 9f / 16 * img.Height) / 2);
int y = 0;
crop = new Rectangle(
x, y, (int)(9f / 16 * img.Height), img.Height);
}
else if ((float)img.Width / img.Height < 9f / 16)
{
int x = 0;
int y = (int)((img.Height - 16f / 9 * img.Width) / 2);
crop = new Rectangle(
x, y, img.Width, (int)(16f / 9 * img.Width));
}
}
if (crop.HasValue)
{
img.Mutate(i => i.Crop(crop.Value));
}
if (img.Width > img.Height && img.Width > 1280)
{
img.Mutate(i => i.Resize(1280, 720));
}
if (img.Width < img.Height && img.Width > 1280)
{
img.Mutate(i => i.Resize(720, 1280));
}
var encoder = new JpegEncoder()
{
Quality = 85
};
img.Save(pathClear, encoder);
var st = System.IO.File.OpenRead(pathClear);
//var st = input.OpenReadStream();
var watermarked = ImageWaterMark.ApplyWaterMark(_config, st);
st.Close();
System.IO.File.WriteAllBytes(path, watermarked);
}
return fileName;
}
catch (Exception e)
{
throw e;
return null;
}
}
====================
ImageWaterMark.cs
====================
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Drawing;
namespace upload_Image_core_img.Models
{
public class ImageWaterMark
{
public static byte[] ApplyWaterMark(IConfiguration config, Stream fStream)
{
//Bitmap using System.Drawing
string watermarkLogo = "watermark-img-myshowtime.png";
string watermarkPath = $"D:/showtime/public/images/wm/{watermarkLogo}";//$"{directory}{watermarkLogo}";
var bitmapTmp = Bitmap.FromStream(fStream);
var bitmap = new Bitmap(bitmapTmp);
using (Graphics grp = Graphics.FromImage(bitmap))
{
var bitmapWM = Bitmap.FromFile(watermarkPath);
Bitmap bmp = new Bitmap(bitmapWM.Width, bitmapWM.Height);
bmp.SetResolution(grp.DpiX, grp.DpiY);
using (Graphics gfx = Graphics.FromImage(bmp))
{
ColorMatrix matrix = new ColorMatrix();
//set the opacity
matrix.Matrix33 = 0.3F;
//create image attributes
ImageAttributes attributes = new ImageAttributes();
//set the color(opacity) of the image
attributes.SetColorMatrix(matrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
//now draw the image
gfx.DrawImage(bitmapWM, new Rectangle(0, 0, bmp.Width, bmp.Height), 0, 0, bitmapWM.Width,
bitmapWM.Height, GraphicsUnit.Pixel, attributes);
}
bitmapWM = bmp;
grp.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
grp.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
grp.DrawImage(bitmap, 0, 0);
int imageH = bitmapWM.Height + 40;
int imageW = bitmapWM.Width + 40;
int jml = bitmap.Height / imageH;
int yStartPos = 0;
int xStartPos = 0;
for (var i = 0; i <= jml; i++)
{
int yPos = yStartPos + (i * imageH);
int jmlX = bitmap.Width / imageW;
for (var j = 0; j <= jmlX; j++)
{
int xPos = xStartPos + (j * imageW);
var posWM = new Point(xPos, yPos);
grp.DrawImage(bitmapWM, posWM);
}
//var posWM = new Point((bitmap.Width / 2) - (bitmapWM.Width / 2), yPos);
//grp.DrawImage(bitmapWM, posWM);
}
var qualityParamId = Encoder.Quality;
var encoderParameters = new EncoderParameters(1);
long quality = 75;
encoderParameters.Param[0] = new EncoderParameter(qualityParamId, quality);
var codec = ImageCodecInfo.GetImageDecoders()
.FirstOrDefault(codec => codec.FormatID == ImageFormat.Jpeg.Guid);
var outStream = new MemoryStream();
bitmap.Save(outStream, codec, encoderParameters);
//bitmap.Save(outStream, bitmap.RawFormat);
var barr = outStream.ToArray();
outStream.Close();
return barr;
//ImageConverter converter = new ImageConverter();
//var bb = (byte[])converter.ConvertTo(tempBitmap, typeof(byte[]));
//return bb;
}
}
}
}
Tidak ada komentar