Image Upload with croping using Jcorp in ASP.NET,C#


Just download the below url about Jcorp plugin,

http://jcrop.org/download
[or]
http://jcrop-cdn.tapmodo.com/archives/jquery.Jcrop-0.9.12.zip
1) Javascript,

<script type=”text/javascript” src=”../js/plugins/jquery-1.11.1.min.js”></script>

<link href=”../css/plugins/jquery.Jcrop.css” rel=”stylesheet” type=”text/css” />

<script src=”../js/plugins/jquery.Jcrop.min.js” type=”text/javascript”></script>

<script src=”../js/plugins/jquery.Jcorp.color.js” type=”text/javascript”></script>

 

<script type=”text/javascript”>

function fnJcrop_reset() {
$(‘#imgLoadded’).data(‘Jcrop’).destroy();
$(‘#imgLoadded’).removeAttr(‘style’);
$(‘#hdImgX’).data(“coords.x”, 0);
$(‘#hdImgY’).data(“coords.y”, 0);
$(‘#hdImgWidth’).data(“coords.w”, 0);
$(‘#hdImgHeight’).data(“coords.h”, 0);
}

var $jcrop_api, $boundX, $boundY,
// Grab some information about the preview pane
$preview = $(‘#imgPreview’),
$pcnt = $(‘#dvPreviewPane’),
$pimg = $(‘#dvPreviewPane img’),
$xsize = $pcnt.width(),
$ysize = $pcnt.height();

var vFileAllowedType = “.jpg,.jpeg,.png,.gif,.bmp”;
var $jcropHandle = null;
$(document).ready(function() {
$(‘#FileUpload1’).change(function() {
var reader = new FileReader();
reader.onload = function(e) {
if (vFileAllowedType.indexOf(e.target.result.split(‘;’)[0].split(‘/’)[1]) == -1) {
alert(“Invalid file format.\n\nPlease choose any .jpg,.jpeg,.png,.gif,.bmp file.”);
return false;
}
if ($jcropHandle != null) {
fnJcrop_reset();
}
$(‘#imgLoadded,#dvPreviewPane,#btnUpload’).show();
$(‘#imgLoadded’).attr(“src”, e.target.result);
$(‘#imgPreview’).attr(“src”, e.target.result);

$jcropHandle = $(‘#imgLoadded’).Jcrop({
onChange: SetCoordinates,

onSelect: SetCoordinates,

onRelease: _hidePreview,
bgOpacity: 0.5,
bgColor: ‘black’, //’white’,
addClass: ‘jcrop-light’,
allowResize: true,
allowMove: true
//,sideHandles: false
// ,aspectRatio: 16 / 9//1
, aspectRatio: 1
}, function() {
                   // Use the API to get the real image size
var bounds = this.getBounds();
$boundX = bounds[0];
$boundY = bounds[1];
$jcrop_api = this; // Store the API in the jcrop_api variable
//api.setSelect([130, 65, 130 + 350, 65 + 285]); \\[left, top, width, height]
$jcrop_api.setSelect([2, 2, 100, 100]);
$jcrop_api.setOptions({
onChange: SetCoordinates,
onSelect: SetCoordinates,
bgFade: true,
minSize: [100, 100]
//,maxSize: [130, 130]
});
$jcrop_api.ui.selection.addClass(‘jcrop-selection’);
                     // Move the preview into the jcrop container for css positioning
$preview.appendTo($jcrop_api.ui.holder);
});
}
reader.readAsDataURL($(this)[0].files[0]);
});

});
function fnImageCorp() {
var x1 = $(‘#hdImgX’).val();
var y1 = $(‘#hdImgY’).val();
var width = $(‘#hdImgWidth’).val();
var height = $(‘#hdImgHeight’).val();
var canvas = $(“#canvas”)[0];
var context = canvas.getContext(‘2d’);
var img = new Image();

img.onload = function() {
canvas.height = height;
canvas.width = width;
context.drawImage(img, x1, y1, width, height, 0, 0, width, height);
$(‘#hdImgCropped’).val(canvas.toDataURL());
$(“#imgPreview”).attr(“src”, canvas.toDataURL());
$(‘[id*=btnUpload]’).show();
};
img.src = $(‘#imgLoadded’).attr(“src”);
}
function _hidePreview() {
$previewImage.stop().fadeOut(‘fast’);
$(“#imgPreview”).attr(‘src’, “../img/profile64x64.jpg”);
}
var $previewImage = $(‘#imgPreview’);
function SetCoordinates(c) {
$(‘#hdImgX’).val(c.x);
$(‘#hdImgY’).val(c.y);
$(‘#hdImgWidth’).val(c.w);
$(‘#hdImgHeight’).val(c.h);
$(‘#btnCrop,#btnClear’).show();

fnImageCorp();

                 //######### about preview #########
if (parseInt(c.w) > 0) {
var rx = $xsize / c.w;
var ry = $ysize / c.h;

$previewImage.css({
width: Math.round(rx * $boundX) + ‘px’,
height: Math.round(ry * $boundY) + ‘px’,
marginLeft: ‘-‘ + Math.round(rx * c.x) + ‘px’,
marginTop: ‘-‘ + Math.round(ry * c.y) + ‘px’
}).show();
}

}

</script>

2) HTML,

for ex : .JPG,.JPEG,.PNG,.GIF,.BMP

 <div class="overflow pLR20 mB18">
 <asp:Image ID="imgViewPhoto" runat="server" AlternateText="NO PREVIEW" ImageUrl="../img/profile64x64.jpg"
 CssClass="fLeft" Style="border: 1px solid #92969a; height: 64px; width: 64px;" />
 <div class="mL10 fLeft">

 <input type="file" id="FileUpload1" accept=".jpg,.jpeg,.png,.gif,.bmp" runat="server" /><br />
 <span>for ex : .JPG,.JPEG,.PNG,.GIF,.BMP</span>
 </div>
 </div>
 <div class="overflow pLR20 mB13">
 <div class="fLeft" style="">
 <p class="mB5">
 Crop</p>
 <div style="width: 400px; height: 330px; border: 1px solid #92969a; overflow: auto;">
 <img id="imgLoadded" src="" alt="" style="display: none;" />
 </div>
 </div>
 <div class="mL18 fLeft" style="width: 64px;">
 <p class="mB5">
 Preview</p>
 <div style="width: 68px; height: 68px; border: 1px solid #92969a;">
 <img alt="" src="../img/profile64x64.jpg" id="imgPreview" style="max-width: 100%;" />
 <canvas id="canvas" height="4" width="5" style="visibility: hidden;"></canvas>
 </div>
 </div>
 </div>
 <hr class="mB13" />
 <div style="margin-left: 20px; float: left;">
 <asp:CheckBox ID="chkIsCropped" runat="server" Text="Without cropped image" />
 </div>
 <div class="overflow pLR20">
 <div class="fRight">
 <input type="hidden" name="hdImgX" id="hdImgX" />
 <input type="hidden" name="hdImgY" id="hdImgY" />
 <input type="hidden" name="hdImgWidth" id="hdImgWidth" />
 <input type="hidden" name="hdImgHeight" id="hdImgHeight" />
 <input type="hidden" name="hdImgCropped" id="hdImgCropped" />
 
 <asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="btnUpload_Click"
 Style="display: none;" CssClass="mL10" OnClientClick="fnUpload_OnClientClick()" />
 </div>
 </div>

SQL Server,

Create table photo (photoid int identity(1,1),photo image)

Handler.ashx,
PhotoViewHandler.ashx,

string strcon = System.Configuration.ConfigurationManager.AppSettings["connStr"].ToString();
public void ProcessRequest(HttpContext context)
{
System.Data.SqlClient.SqlConnection connection = new System.Data.SqlClient.SqlConnection(strcon);
connection.Open();
System.Data.SqlClient.SqlCommand command = new System.Data.SqlClient.SqlCommand("select imageTypePhoto from photo where iPhotoId=" + Convert.ToInt32(context.Request.QueryString["qstrPhotoId"].ToString()), connection);
System.Data.SqlClient.SqlDataReader dr = command.ExecuteReader();
dr.Read();
context.Response.BinaryWrite((Byte[])dr[0]);
connection.Close();
context.Response.End();
}

C#,

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
imgViewPhoto.ImageUrl = "PhotoViewHandler.ashx?qstrPhotoId=" + dtGetEmpInfo.Rows[0]["emp_iPhotoId"].ToString();
}
}
private byte[] imageToByteArray(System.Drawing.Image imageIn)
{
MemoryStream ms = new MemoryStream();
imageIn.Save(ms, imageIn.RawFormat);
return ms.ToArray();
}
protected void btnUpload_Click(object sender, EventArgs e)
{
try
{
if (!chkIsCropped.Checked)
{
string strCropImgBase64 = Request.Form["hdImgCropped"];
byte[] bByteArray = Convert.FromBase64String(strCropImgBase64.Split(',')[1]);

//using (FileStream stream = new FileStream(Server.MapPath("~/cropped-images/" + Session["_UserID"].ToString() + ".png"), FileMode.Create))
string strFileDir = Path.Combine(System.Configuration.ConfigurationSettings.AppSettings["e-Profile-cropped-images"].ToString(), Session["_UserID"].ToString());
string strFileName = Session["_UserID"].ToString() + ".png";

if (File.Exists(Path.Combine(strFileDir, strFileName)))
{
System.IO.File.Delete(Path.Combine(strFileDir, strFileName));
}

CreateUserDir(strFileDir, strFileName);
using (FileStream stream = new FileStream(Path.Combine(strFileDir, strFileName), FileMode.Create))
{
stream.Write(bByteArray, 0, bByteArray.Length);
stream.Flush();
}

string strCroppedFilePath = Path.Combine(strFileDir, strFileName);
System.Drawing.Image orgCroppedImg = System.Drawing.Image.FromFile(strCroppedFilePath);

string strRes = eFun.InsertPhoto(imageToByteArray(orgCroppedImg));
}
else
{
if (Request.Files["FileUpload1"] != null)
{
HttpPostedFile MyFile = Request.Files["FileUpload1"];

Byte[] bImageData = null;
if (MyFile.ContentLength > 0)
{
Stream str = FileUpload1.PostedFile.InputStream;
BinaryReader br = new BinaryReader(str);
bImageData = br.ReadBytes((int)str.Length);
}
string strRes = eFun.InsertPhoto(bImageData);
}
}
}
catch(Exception ex)
{
}
}
#region Create User Directory
///
/// Create user Directory If doesn't exist
///

/////////
public static string CreateUserDir(string strPathDir, string strFileName)
{
//Create a Instance for Directory Info
DirectoryInfo dirInfo = new DirectoryInfo(strPathDir);

//Check with the user Directory, if exist or doesn't exist
if (dirInfo.Exists)
{
strFileName = Path.Combine(strPathDir, strFileName);
}
else
{
dirInfo.Create();
strFileName = Path.Combine(strPathDir, strFileName);
}
return strFileName;
}
#endregion

Get Numeric & Special char with inside the text


Declare @tblTemp table (vData varchar(50))
insert into @tblTemp(vData) values('abc')
insert into @tblTemp(vData) values('abc%')
insert into @tblTemp(vData) values('a%c')
insert into @tblTemp(vData) values('123')
insert into @tblTemp(vData) values('45')
select * from @tblTemp

-- Get the data with inside the text like '%'
select * from @tblTemp where vData LIKE '%[%]'

-- Get the Numeric data
select * from @tblTemp WHERE vData not like '%[^0-9]%'
-- [Or]
select * from @tblTemp where ISNUMERIC(vData)=1

XML Value passes in Table valued functions in SQL Server


create function dbo.ReadXml (@xmlMatrix xml)
returns table
as
return
(
select t.value(‘./@Salary’, ‘integer’) as Salary,
t.value(‘./@Age’, ‘integer’) as Age
from @xmlMatrix.nodes(‘//row’) x(t)
)
GO
—————————————————
declare @source table(Salary integer,age tinyint)

insert into @source
select 10000, 25 union all
select 15000, 27 union all
select 12000, 18 union all
select 15000, 36 union all
select 16000, 57 union all
select 17000, 44 union all
select 18000, 32 union all
select 19000, 56 union all
select 25000, 34 union all
select 7500, 29
–select * from @source
———————————————————-

declare @functionArgument xml

select @functionArgument =
(
select Salary as [row/@Salary],Age as [row/@Age]
from @source for xml path(”)
)
–select @functionArgument as [@functionArgument]

select * from ReadXml(@functionArgument)

Reference :

http://stackoverflow.com/questions/1609115/pass-table-as-parameter-into-sql-server-udf

Enable & Disable Triggers in SQL Server


— Triggers
—————–
SELECT * FROM sys.triggers
WHERE is_disabled = 0 — Enabled
ORDER BY [Name]
GO

–Enable Trigger
ENABLE TRIGGER [trgDDLMonitoring] ON DATABASE

–Enable Trigger in Particular Table
ENABLE TRIGGER DataBaseName.TriggerName ON DataBaseName.TableName

–Disable Trigger
DISABLE TRIGGER [trgDDLMonitoring] ON DATABASE

–Disable Trigger in Particular Table
DISABLE TRIGGER DataBaseName.TriggerName ON DataBaseName.TableName

— Disable & Enable all the triggers for all servers:
DISABLE TRIGGER ALL ON ALL SERVER;
ENABLE TRIGGER ALL ON ALL SERVER;
—————–

Search Text in Stored Procedures in SQL Server


— Search Text in Stored Procedures
————————————
SELECT DISTINCT
o.name AS Object_Name,
o.type_desc
FROM sys.sql_modules m
INNER JOIN
sys.objects o
ON m.object_id = o.object_id
WHERE m.definition Like ‘%TEXT%’ ESCAPE ‘\’

%d bloggers like this: