2. Uploadify.ashx
'PP > Upload' 카테고리의 다른 글
실시간 파일 업로드 - uploadify (0) | 2012.01.04 |
---|
실시간 파일 업로드 - uploadify (0) | 2012.01.04 |
---|
In this article I am going to show how to resize image dynamically or making thumbnail dynamically with ashx file.Start new website project give name thumbnail.In menu go to Webite > Add new item and select Generic Handler. Name it Handler.ashx, You will get auto generated code in it like given below:
<%@ WebHandler Language="C#" Class="Handler" %>
using System;
using System.Web;
public class Handler : IHttpHandler {
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "text/plain";
context.Response.Write("Hello World");
}
public bool IsReusable {
get {
return false;
}
}
}
Now add given namespace to handle the image files
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
Make a new folder for images files, name it images. Put some images in this folder.
Now our next step is getting the height , width , image name and changing image size.
To do these things, here query string is used. In ProcessRequest method write follwing lines.
public class Handler : IHttpHandler {
public void ProcessRequest (HttpContext context) {
// for new height of image
int h=int.Parse(context.Request.QueryString["h"].ToString());
// for new width of image
int w = int.Parse(context.Request.QueryString["w"].ToString());
// for image file name
string file = context.Request.QueryString["file"].ToString();
// Path of image folder where images files are placed
string filePath = context.Server.MapPath("~/images/" + file);
// Resize proccess
using(System.Drawing.Image img=System.Drawing.Image.FromFile(filePath))
{
Bitmap objBmp = new Bitmap(img,w, h);
string extension = Path.GetExtension(filePath);
MemoryStream ms;
byte[] bmpBytes;
switch (extension.ToLower())
{
case ".jpg":
case ".jpeg":
ms = new MemoryStream();
objBmp.Save(ms, ImageFormat.Jpeg);
bmpBytes = ms.GetBuffer();
context.Response.ContentType = "image/jpeg";
context.Response.BinaryWrite(bmpBytes);
objBmp.Dispose();
ms.Close();
context.Response.End();
break;
case ".png":
ms = new MemoryStream();
objBmp.Save(ms, ImageFormat.Png);
bmpBytes = ms.GetBuffer();
context.Response.ContentType = "image/png";
context.Response.BinaryWrite(bmpBytes);
objBmp.Dispose();
ms.Close();
context.Response.End();
break;
case ".gif":
ms = new MemoryStream();
objBmp.Save(ms, ImageFormat.Gif);
bmpBytes = ms.GetBuffer();
context.Response.ContentType = "image/png";
context.Response.BinaryWrite(bmpBytes);
objBmp.Dispose();
ms.Close();
context.Response.End();
break;
}
img.Dispose();
}
}
Now we move to Default.aspx page, drag here Image tool from tool box :
<asp:Image ID="img1" runat="server" /><br />
For retriving the image set ImageUrl as given below with height width and image name.
<asp:Image ID="img1" runat="server" ImageUrl="~/Handler.ashx?h=50&w=50&file=Winter.jpg" /><br />
And now finally run the default.aspx and see the result.
[출처] [asp.net] ashx 이미지 섬네일|작성자 괴무리
[캐싱] 데이터 캐싱 Tips - Context.Cache (0) | 2012.01.08 |
---|---|
[캐싱] 데이터 캐싱 - Response.Cache.XXX (0) | 2012.01.08 |
[asp.net] 이미지 섬네일 (0) | 2012.01.06 |
C# 이미지 섬네일 (0) | 2012.01.06 |
[.ASHX 파일]jQuery 제너릭 처리기(ashx)로 DB/데이터배이스 받기/사용 핸들러/handler (0) | 2012.01.06 |
출처 : http://www.west-wind.com/weblog/posts/283.aspx
One frequent task is to take images and convert them into thumbnails. This is certainly nothing new, but seeing this question is so frequently asked on newsgroups and message boards bears reviewing this topic here again.
I was getting tired of constantly repeating this code for specific situations, so I created a generic page in my apps to handle resizing images from the current site dynamically in a page called CreateThumbnail. You call this page with a relative image name from the Web site on the querystring and it returns the image as a thumbnail.
An example of how this might work looks like this:
Size is an optional second parameter – it defaults to 120.
Here’s what the implementation of this generic page looks like:
using System.Drawing;
using System.Drawing.Imaging;
…
public class CreateThumbNail : System.Web.UI.Page
{
private void Page_Load(object sender, System.EventArgs e)
{
string Image = Request.QueryString["Image"];
if (Image == null)
{
this.ErrorResult();
return;
}
string sSize = Request["Size"];
int Size = 120;
if (sSize != null)
Size = Int32.Parse(sSize);
string Path = Server.MapPath(Request.ApplicationPath) + "\\" + Image;
Bitmap bmp = CreateThumbnail(Path,Size,Size);
if (bmp == null)
{
this.ErrorResult();
return;
}
string OutputFilename = null;
OutputFilename = Request.QueryString["OutputFilename"];
if (OutputFilename != null)
{
if (this.User.Identity.Name == "")
{
// *** Custom error display here
bmp.Dispose();
this.ErrorResult();
}
try
{
bmp.Save(OutputFilename);
}
catch(Exception ex)
{
bmp.Dispose();
this.ErrorResult();
return;
}
}
// Put user code to initialize the page here
Response.ContentType = "image/jpeg";
bmp.Save(Response.OutputStream,System.Drawing.Imaging.ImageFormat.Jpeg);
bmp.Dispose();
}
private void ErrorResult()
{
Response.Clear();
Response.StatusCode = 404;
Response.End();
}
///
/// Creates a resized bitmap from an existing image on disk.
/// Call Dispose on the returned Bitmap object
///
///
///
///
///
public static Bitmap CreateThumbnail(string lcFilename,int lnWidth, int lnHeight)
{
System.Drawing.Bitmap bmpOut = null;
try
{
Bitmap loBMP = new Bitmap(lcFilename);
ImageFormat loFormat = loBMP.RawFormat;
decimal lnRatio;
int lnNewWidth = 0;
int lnNewHeight = 0;
//*** If the image is smaller than a thumbnail just return it
if (loBMP.Width < lnWidth && loBMP.Height < lnHeight)
return loBMP;
if (loBMP.Width > loBMP.Height)
{
lnRatio = (decimal) lnWidth / loBMP.Width;
lnNewWidth = lnWidth;
decimal lnTemp = loBMP.Height * lnRatio;
lnNewHeight = (int)lnTemp;
}
else
{
lnRatio = (decimal) lnHeight / loBMP.Height;
lnNewHeight = lnHeight;
decimal lnTemp = loBMP.Width * lnRatio;
lnNewWidth = (int) lnTemp;
}
// System.Drawing.Image imgOut =
// loBMP.GetThumbnailImage(lnNewWidth,lnNewHeight,
// null,IntPtr.Zero);
// *** This code creates cleaner (though bigger) thumbnails and properly
// *** and handles GIF files better by generating a white background for
// *** transparent images (as opposed to black)
bmpOut = new Bitmap(lnNewWidth, lnNewHeight);
Graphics g = Graphics.FromImage(bmpOut);
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
g.FillRectangle( Brushes.White,0,0,lnNewWidth,lnNewHeight);
g.DrawImage(loBMP,0,0,lnNewWidth,lnNewHeight);
loBMP.Dispose();
}
catch
{
return null;
}
return bmpOut;
}
}
This code doesn’t use the CreateThumbnail method of GDI+ because it doesn’t properly convert transparent GIF images as it draws the background color black. The code above compensates for this by first drawing the canvas white then loading the GIF image on top of it. Transparency is lost – unfortunately GDI+ does not handle transparency automatically and keeping Transparency intact requires manipulating the palette of the image which is beyond this demonstration.
The Bitmap object is returned as the result. You can choose what to do with this object. In this example it’s directly streamed in the ASP. Net Output stream by default. If you specify another query string value of OutputFilename you can also force the file to be written to disk *if* you are logged in. This is definitely not something that you want to allow just ANY user access to as anything that writes to disk is potentially dangerous in terms of overloading your disk space. Writing files out in this fashion also requires that the ASPNET or NETWORK SERVICE or whatever account the ASP. Net app runs under has rights to write the file in the specified directory. I’ve provided this here as an example, but it’s probably best to stick file output functionality into some other more isolated component or page that is more secure.
Notice also that all errors return a 404 file not found error. This is so that images act on failure just as if an image file is not available which gives the browser an X’d out image to display. Realistically this doesn’t matter – browsers display the X anyway even if you send back an HTML error message, but this is the expected response the browser would expect.
In my West Wind Web Store I have several admin routines that allow to resize images on the fly and display them in a preview window. It’s nice to preview them before writing them out to disk optionally. You can also do this live in an application *if* the number of images isn’t very large and you’re not pushing your server to its limits already. Image creation on the fly is always slower than static images on disk. However, ASP. Net can be pretty damn efficient using Caching and this scenario is made for it. You can specify:
<%@ OutputCache duration="10000" varybyparam="Image;Size" %>
in the ASPX page to force images to cache once they’ve been generated. This will work well, but keep in mind that bitmap images can be memory intensive and caching them can add up quickly especially if you have large numbers of them.
[출처] [asp.net] 이미지 섬네일|작성자 괴무리
[캐싱] 데이터 캐싱 - Response.Cache.XXX (0) | 2012.01.08 |
---|---|
[asp.net] ashx 이미지 섬네일 (0) | 2012.01.06 |
C# 이미지 섬네일 (0) | 2012.01.06 |
[.ASHX 파일]jQuery 제너릭 처리기(ashx)로 DB/데이터배이스 받기/사용 핸들러/handler (0) | 2012.01.06 |
GENERIC (0) | 2012.01.04 |
출처 : http://ryunad.tistory.com/tag/C%23%20%EC%9D%B4%EB%AF%B8%EC%A7%80%20%EC%8D%B8%EB%84%A4%EC%9D%BC
간단하게 이미지를 하나 선택하면 선택한 이미지의 Thumbnail을 만드는 로직입니다.
윈 폼으로 만들었지만 로직부분만 재활용하면 ASP.NET이든 WPF든 어디서든 사용이 가능합니다.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
namespace Ex11
{
public partial class MainForm : Form
{
private Person _person = new Person();
public MainForm()
{
InitializeComponent();
}
private void btnLoadPicture_Click(object sender, EventArgs e)
{
//1. 파일 불러오기
OpenFileDialog dlg = new OpenFileDialog();
if (DialogResult.OK == dlg.ShowDialog())
{
string path = Application.StartupPath;
string fileName =
dlg.FileName.Substring(
dlg.FileName.LastIndexOf("\\") + 1);
string filePath =
Path.Combine(path, fileName);
int dotPosition = fileName.LastIndexOf(".");
string thumbnailName =
fileName.Substring(0, dotPosition) +
"_small" +
fileName.Substring(dotPosition);
string thumbnailPath =
Path.Combine(path, thumbnailName);
if (File.Exists(filePath))
File.Delete(filePath);
//2. 원본이미지 복사 및 thumbnail 이미지 생성
File.Copy(dlg.FileName, filePath);
Image image =
Image.FromFile(filePath);
Image thumbnail =
image.GetThumbnailImage(150, 150, null, IntPtr.Zero);
//picture 이미지 해제
if (pbPicture.Image != null)
{
pbPicture.Image.Dispose();
}
if (File.Exists(thumbnailPath))
File.Delete(thumbnailPath);
thumbnail.Save(thumbnailPath);
//이미지 객체의 해제
image.Dispose();
thumbnail.Dispose();
//3. 이미지 표시
pbPicture.Image =
Image.FromFile(thumbnailPath);
_person.ImagePath = fileName;
}
}
private void miSave_Click(object sender, EventArgs e)
{
_person.Name = txtName.Text;
_person.ResidentNumbers = txtResidentNumber.Text;
_person.BirthDate = DateTime.Parse(txtBirthDate.Text);
_person.Height = int.Parse(txtHeight.Text);
_person.Weight = int.Parse(txtWeight.Text);
_person.Phone = txtPhone.Text;
_person.Email = txtEmail.Text;
string path = Path.Combine(Application.StartupPath, "person.dat"); ;
FileStream stream = new FileStream(path, FileMode.Create);
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(stream, _person);
stream.Close();
MessageBox.Show("저장되었습니다.");
}
private void miOpen_Click(object sender, EventArgs e)
{
}
private void MainForm_Load(object sender, EventArgs e)
{
string path = Path.Combine(Application.StartupPath,"person.dat");
if (File.Exists(path))
{
FileStream stream = new FileStream(path, FileMode.Open);
BinaryFormatter formatter = new BinaryFormatter();
_person = (Person)formatter.Deserialize(stream);
txtName.Text = _person.Name;
txtResidentNumber.Text = _person.ResidentNumbers;
txtBirthDate.Text = _person.BirthDate.ToString("yyyy-MM-dd");
txtHeight.Text = _person.Height.ToString();
txtWeight.Text = _person.Weight.ToString();
txtPhone.Text = _person.Phone;
txtEmail.Text = _person.Email;
string fileName = _person.ImagePath;
fileName = fileName.Insert(fileName.LastIndexOf("."), "_small");
string imagePath = Path.Combine(Application.StartupPath, fileName);
if (File.Exists(imagePath))
{
pbPicture.Image = Image.FromFile(imagePath);
}
}
}
}
}
[출처] C# 이미지 섬네일|작성자 괴무리
[asp.net] ashx 이미지 섬네일 (0) | 2012.01.06 |
---|---|
[asp.net] 이미지 섬네일 (0) | 2012.01.06 |
[.ASHX 파일]jQuery 제너릭 처리기(ashx)로 DB/데이터배이스 받기/사용 핸들러/handler (0) | 2012.01.06 |
GENERIC (0) | 2012.01.04 |
Generic (0) | 2012.01.04 |
[asp.net] ashx 이미지 섬네일 (0) | 2012.01.06 |
---|---|
[asp.net] 이미지 섬네일 (0) | 2012.01.06 |
C# 이미지 섬네일 (0) | 2012.01.06 |
GENERIC (0) | 2012.01.04 |
Generic (0) | 2012.01.04 |
Socket server & client 흐름. (0) | 2012.01.06 |
---|---|
실행하는 컴퓨터의 IP를 찾아 종점을 생성 (0) | 2012.01.06 |
[Socket] Server & Client With Consol : Receive and Send (0) | 2012.01.06 |
[Socket] Server & Client using Console. (0) | 2012.01.06 |
[IO] Stream 의 파생 클래스 (0) | 2012.01.06 |
---|---|
실행하는 컴퓨터의 IP를 찾아 종점을 생성 (0) | 2012.01.06 |
[Socket] Server & Client With Consol : Receive and Send (0) | 2012.01.06 |
[Socket] Server & Client using Console. (0) | 2012.01.06 |
public void Listen()
{
adtx ad = new adtx(textBox1.AppendText);
IPAddress addr = new IPAddress(0);
TcpListener server = new TcpListener(addr, 5425);
server.Start();
Invoke(ad, "서버시작");
...
}
Listen() 메소드는 별도의 작업자 쓰레드가 실행하는 메소드입니다.
즉, Listen() 메소드는 메인 쓰레드가 아닌 다른 쓰레드에서 실행됩니다.
그러므로,
Listen() 메소드의 코드는 별도의 작업자 쓰레드 상에서 실행되며,
메인 쓰레드에서 생성된 컨트롤에는 접근할 수 없습니다.
그렇지만,
Invoke(ad, "서버시작");
메소드 호출을 통해, 간접적으로 메인 쓰레드의 컨트롤에 접근할 수 있습니다.
위의 문장은
this.Invoke(ad, "서버시작");
다음과 같습니다.
여기서, this 참조는 Form 개체를 가리키는 것이지요.
별도의 쓰레드에서 메인 쓰레드의 컨트롤에 접근하려면,
Form 개체의 Invoke() 메소드를 호출하면 되는 구나~~
하고 알고 계시면 되겠습니다.
제네릭 처리기를 이용하여 자동가입방지 폼 구현 (0) | 2012.01.07 |
---|---|
C# 인터넷 연결 체크하기 (0) | 2012.01.07 |
자동 업데이트 (0) | 2012.01.07 |
HttpContext, HttpWebRequest, HttpWebResponse, Application 등의 경로 (0) | 2012.01.07 |
String <-> byte[] 변환 (0) | 2012.01.06 |
[IO] Stream 의 파생 클래스 (0) | 2012.01.06 |
---|---|
Socket server & client 흐름. (0) | 2012.01.06 |
[Socket] Server & Client With Consol : Receive and Send (0) | 2012.01.06 |
[Socket] Server & Client using Console. (0) | 2012.01.06 |
[IO] Stream 의 파생 클래스 (0) | 2012.01.06 |
---|---|
Socket server & client 흐름. (0) | 2012.01.06 |
실행하는 컴퓨터의 IP를 찾아 종점을 생성 (0) | 2012.01.06 |
[Socket] Server & Client using Console. (0) | 2012.01.06 |
[IO] Stream 의 파생 클래스 (0) | 2012.01.06 |
---|---|
Socket server & client 흐름. (0) | 2012.01.06 |
실행하는 컴퓨터의 IP를 찾아 종점을 생성 (0) | 2012.01.06 |
[Socket] Server & Client With Consol : Receive and Send (0) | 2012.01.06 |
String -> byte[] 로 변환하는 방법
String str = "string test data " ; byte[] result = System.Text.Encoding.Default.GetBytes( str ); |
- byte[] -> String 로 변환하는 방법
byte[] byte1 = System.Text.Encoding.Default.GetBytes( "byte test data" ); String result = System.Text.Encoding.Default.GetString( byte1 ); |
ps) 상황에 따라 엔코딩 방벙에는 Default, Unicode, UTF8, UTF16, UTF32등으로 사용 할 수 있다 .
제네릭 처리기를 이용하여 자동가입방지 폼 구현 (0) | 2012.01.07 |
---|---|
C# 인터넷 연결 체크하기 (0) | 2012.01.07 |
자동 업데이트 (0) | 2012.01.07 |
HttpContext, HttpWebRequest, HttpWebResponse, Application 등의 경로 (0) | 2012.01.07 |
this.Invoke 관련 (0) | 2012.01.06 |