티스토리 툴바



2011/05/01 22:34

카메라 연동 코드 (UIImagePickerController)

[기능]
- 카메라를 통한 사진 선택
- 롤 이미지에서 사진 선택
- 도큐먼트에 이미지 저장
- 새로 실행할때 도큐먼트 이미지 로드 기능

-h 코드

//

//  DocumentTestViewController.h

//  DocumentTest

//

//  Created by 병욱 on 11. 5. 1..

//  Copyright 2011 GsiSystem. All rights reserved.

//


#import <UIKit/UIKit.h>


#define kFilename @"data.plist"

#define kImageFilename @"Test.png"


@interface DocumentTestViewController : UIViewController<UIImagePickerControllerDelegate, UINavigationControllerDelegate> {

IBOutlet UIImageView *imageView;

IBOutlet UIButton *takePictureButton;

IBOutlet UIButton *selectFromCameraRollButton;

IBOutlet UITextField *field1;

IBOutlet UITextField *field2;

IBOutlet UITextField *field3;

IBOutlet UITextField *field4;

}


@property (nonatomic, retain) UIImageView *imageView;

@property (nonatomic, retain) UIButton *takePictureButton;

@property (nonatomic, retain) UIButton *selectFromCameraRollButton;


@property (nonatomic, retain) UITextField *field1;

@property (nonatomic, retain) UITextField *field2;

@property (nonatomic, retain) UITextField *field3;

@property (nonatomic, retain) UITextField *field4;


- (NSString *)dataFilePath;

- (NSString *)dataImageFilePath;

- (void) applicationWillTerminate:(NSNotification *)notification;

- (IBAction)getCameraPicture:(id)sender;

- (IBAction)selectExistingPicture;


@end


- m 코드

//

//  DocumentTestViewController.m

//  DocumentTest

//

//  Created by 병욱 on 11. 5. 1..

//  Copyright 2011 GsiSystem. All rights reserved.

//


#import "DocumentTestViewController.h"


@implementation DocumentTestViewController


@synthesize field1, field2, field3, field4;

@synthesize imageView;

@synthesize takePictureButton;

@synthesize selectFromCameraRollButton;


/*

// The designated initializer. Override to perform setup that is required before the view is loaded.

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {

    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];

    if (self) {

        // Custom initialization

    }

    return self;

}

*/


/*

// Implement loadView to create a view hierarchy programmatically, without using a nib.

- (void)loadView {

}

*/


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.

- (void)viewDidLoad {

//    [super viewDidLoad];

//

NSString *filePath = [self dataFilePath];

if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {

NSArray *array = [[NSArray alloc] initWithContentsOfFile:filePath];

field1.text = [array objectAtIndex:0];

field2.text = [array objectAtIndex:1];

field3.text = [array objectAtIndex:2];

field4.text = [array objectAtIndex:3];

[array release];

}

//

NSString *imageFilePath = [self dataImageFilePath];

if ([[NSFileManager defaultManager] fileExistsAtPath:imageFilePath]) {

UIImage *image = [UIImage imageWithContentsOfFile:imageFilePath];

imageView.image = image;

}

//

UIApplication *app = [UIApplication sharedApplication];

[[NSNotificationCenter defaultCenter] addObserver:self 

selector:@selector(applicationWillTerminate:) 

name:UIApplicationWillTerminateNotification 

  object:app];

[super viewDidLoad];

//

if (![UIImagePickerController isSourceTypeAvailable:

  UIImagePickerControllerSourceTypeCamera]) {

takePictureButton.hidden = YES;

selectFromCameraRollButton.hidden = YES;

}

}


- (NSString *)dataFilePath

{

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *documentsDirectory = [paths objectAtIndex:0];

return [documentsDirectory stringByAppendingPathComponent:kFilename];

}


- (NSString *)dataImageFilePath

{

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *documentsDirectory = [paths objectAtIndex:0];

return [documentsDirectory stringByAppendingPathComponent:kImageFilename];

}


- (void) applicationWillTerminate:(NSNotification *)notification

{

NSMutableArray *array = [[NSMutableArray alloc] init];

[array addObject:field1.text];

[array addObject:field2.text];

[array addObject:field3.text];

[array addObject:field4.text];

[array writeToFile:[self dataFilePath] atomically:YES];

[array release];

}


/*

// Override to allow orientations other than the default portrait orientation.

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {

    // Return YES for supported orientations

    return (interfaceOrientation == UIInterfaceOrientationPortrait);

}

*/


- (void)didReceiveMemoryWarning {

// Releases the view if it doesn't have a superview.

    [super didReceiveMemoryWarning];

// Release any cached data, images, etc that aren't in use.

}


- (void)viewDidUnload {

// Release any retained subviews of the main view.

// e.g. self.myOutlet = nil;

}



- (void)dealloc {

    [super dealloc];

[field1 release];

[field2 release];

[field3 release];

[field4 release];

[imageView release];

[takePictureButton release];

[selectFromCameraRollButton release];

}


- (IBAction)getCameraPicture:(id)sender

{

UIImagePickerController *picker = 

[[UIImagePickerController alloc] init];

picker.delegate = self;

picker.allowsImageEditing = YES;

picker.sourceType = (sender == takePictureButton) ?

UIImagePickerControllerSourceTypeCamera

UIImagePickerControllerSourceTypeSavedPhotosAlbum;

[self presentModalViewController:picker animated:YES];

[picker release];

}


- (IBAction)selectExistingPicture

{

if ([UIImagePickerController isSourceTypeAvailable:

UIImagePickerControllerSourceTypePhotoLibrary]) {

UIImagePickerController *picker = 

[[UIImagePickerController alloc] init];

picker.delegate = self;

picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;

picker.allowsImageEditing = YES;

[self presentModalViewController:picker animated:YES];

[picker release];

}

else {

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error accessing photo library"

message:@"Device does not support a photo library"

  delegate:nil

  cancelButtonTitle:@"Drat!"

  otherButtonTitles:nil];

[alert show];

[alert release];

}

}


- (void)imagePickerController:(UIImagePickerController *)picker

didFinishPickingImage:(UIImage *)image

  editingInfo:(NSDictionary *)editingInfo {

imageView.image = image;

printf("Image:%f, %f", image.size.width, image.size.height);

[UIImagePNGRepresentation(image) writeToFile:[self dataImageFilePath]

  atomically:YES];

[picker dismissModalViewControllerAnimated:YES];

}


- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker

{

[picker dismissModalViewControllerAnimated:YES];

}


@end


- 인터페이스 빌더 내용
캡춰 맥에서 어케 하는지 몰겠군요. ^^
 
저작자 표시 비영리 변경 금지
크리에이티브 커먼즈 라이선스
Creative Commons License
Trackback 0 Comment 2
2011/04/25 17:50

iphone에서 http 사용하기 (get/post) - 소스코드는 퍼왔습니다.

POST로 데이터를 보낼때 NSDictionary를 사용하면 되는데 스타일은
아래의 코드와 같이 실제 값이 앞에 가고 뒤에 이름이 들어간다.

[뷰에 클릭후 http를 생성 및 초기 코드]

// url 문자열을 이용하여 HTTP 웹사이트에 접속

- (void)requestUrl {

    // 접속할 주소 설정

    NSString *url = @"http://사용자의 웹 페이지 주소";

    

    // HTTP Request 인스턴스 생성

    HTTPRequest *httpRequest = [[HTTPRequest alloc] init];

    

    // POST 전송할 데이터 설정

    NSDictionary *bodyObject = [NSDictionary dictionaryWithObjectsAndKeys:

@"38.0", @"latitude"

@"127.0", @"longitude",

nil];

//NSString *bodyObject = @"type=getUser&seq=1&latitude=38.0&longitude=127.0&time=13600&unit='k'&distance=9999";

    

    // 통신 완료 호출할 델리게이트 셀렉터 설정

    [httpRequest setDelegate:self selector:@selector(didReceiveFinished:)];

    

    // 페이지 호출

    [httpRequest requestUrl:url bodyObject:bodyObject];

//

[spinner startAnimating];

}


아래 코드들은 클래스 생성후에 내용을 추가 해야 합니다.
[HTTPRequest.h]

#import <Foundation/Foundation.h>



@interface HTTPRequest : NSObject

{

    NSMutableData *receivedData;

    NSURLResponse *response;

    NSString *result;

    id target;

    SEL selector;

}


- (BOOL)requestUrl:(NSString *)url bodyObject:(NSDictionary *)bodyObject;

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)aResponse;

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data;

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error;

- (void)connectionDidFinishLoading:(NSURLConnection *)connection;

- (void)setDelegate:(id)aTarget selector:(SEL)aSelector;


@property (nonatomic, retain) NSMutableData *receivedData;

@property (nonatomic, retain) NSURLResponse *response;

@property (nonatomic, assign) NSString *result;

@property (nonatomic, assign) id target;

@property (nonatomic, assign) SEL selector;


@end



[HTTPRequest.m]

#import "HTTPRequest.h"


@implementation HTTPRequest


@synthesize receivedData;

@synthesize response;

@synthesize result;

@synthesize target;

@synthesize selector;


- (BOOL)requestUrl:(NSString *)url bodyObject:(NSDictionary *)bodyObject

{

    // URL Request 객체 생성

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]

                                                           cachePolicy:NSURLRequestUseProtocolCachePolicy

                                                       timeoutInterval:5.0f];

    

    // 통신방식 정의 (POST, GET)

    [request setHTTPMethod:@"POST"];

    

    // bodyObject 객체가 존재할 경우 QueryString형태로 변환

    if(bodyObject)

    {

        // 임시 변수 선언

        NSMutableArray *parts = [NSMutableArray array];

        NSString *part;

        id key;

        id value;

        

        // 값을 하나하나 변환

        for(key in bodyObject)

        {

            value = [bodyObject objectForKey:key];

            part = [NSString stringWithFormat:@"%@=%@", [key stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],

[value stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];

            [parts addObject:part];

        }

        

        // 값들을 & 연결하여 Body 사용

        [request setHTTPBody:[[parts componentsJoinedByString:@"&"] dataUsingEncoding:NSUTF8StringEncoding]];

    }

    

    // Request 사용하여 실제 연결을 시도하는 NSURLConnection 인스턴스 생성

    NSURLConnection *connection = [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];

    

    // 정상적으로 연결이 되었다면

    if(connection)

    {

        // 데이터를 전송받을 멤버 변수 초기화

        receivedData = [[NSMutableData alloc] init];

        return YES;

    }

    

    return NO;

}


- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)aResponse

{

    // 데이터를 전송받기 전에 호출되는 메서드, 우선 Response 헤더만을 먼저 받아 온다.

    //[receivedData setLength:0];

    self.response = aResponse;

}


- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data

{

    // 데이터를 전송받는 도중에 호출되는 메서드, 여러번에 나누어 호출될 있으므로 appendData 사용한다.

    [receivedData appendData:data];

}


- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error

{

    // 에러가 발생되었을 경우 호출되는 메서드

    NSLog(@"Error: %@", [error localizedDescription]);

}


- (void)connectionDidFinishLoading:(NSURLConnection *)connection

{

    // 데이터 전송이 끝났을 호출되는 메서드, 전송받은 데이터를 NSString형태로 변환한다.

    result = [[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding];

    

    // 델리게이트가 설정되어있다면 실행한다.

    if(target)

    {

        [target performSelector:selector withObject:result];

    }

}


- (void)setDelegate:(id)aTarget selector:(SEL)aSelector

{

    // 데이터 수신이 완료된 이후에 호출될 메서드의 정보를 담고 있는 셀렉터 설정

    self.target = aTarget;

    self.selector = aSelector;

}


- (void)dealloc

{

    [receivedData release];

    [response release];

    [result release];

    [super dealloc];

}


@end


 
저작자 표시 비영리 변경 금지
크리에이티브 커먼즈 라이선스
Creative Commons License
Trackback 0 Comment 0
2010/01/01 23:29

CxImage의 MakeBitmap를 잘못 사용하면 페이지파일(PF), 메모리 사용량이 늘어난다.


MFC의 Dialog 베이스를 사용해서 폼을 하나 제작합니다.
그리고 picture Box 를 하나 제작한 후에 CxImage를 사용해서 png 파일을 하나 로드 한후에
picture Box에 SetBitmap 를 하고 나서 이걸 다른 형태로 테스트를 진행해 봤습니다.

기본 코드는 아래와 같아요.

// CxImage 객체 생성
m_pImage = new CxImage("D:\\Test.png", CXIMAGE_FORMAT_PNG);

// PictureBox 컨트롤에 CxImage 이미지 연동
m_pic.SetBitmap( m_pImage->MakeBitmap() );

이렇게 하고 나서 실행 하고, 종료 하게 되면 크게 문제는 안되는듯 하다.

이걸 다른 형태로 테스트를 해봤다.
타이머를 통해서 CxImage 객체 두개의 Bitmap를 m_pic(PictureBox) 컨트롤에 SetBitmap를 반복해서 처리해봤다.

void CPngToBitmapDlg::OnTimer(UINT nIDEvent)
{
 static bool bFirst = false;
 static HBITMAP hBitmap = NULL;

 if( bFirst == false )
 { 
  hBitmap = m_pic.SetBitmap( m_pImage2->MakeBitmap() );
 }
 else
 {
  hBitmap = m_pic.SetBitmap( m_pImage->MakeBitmap() );
 }

 ::DeleteObject( hBitmap );

 //
 bFirst = !bFirst;

 m_loopCount++;
 UpdateData(false);
 

 CDialog::OnTimer(nIDEvent);
}

위의 붉은색 코드를 하지 않고 계속해서 SetBitmap을 하게 되면
페이지파일(PF)가 계속 증가 하는 것을 볼 수 있다.

앞으로 코드 구현을 할때 하나 하나 단위테스트를 통해서 반복적인 메모리 및 GDI 사용량 등을
체크 하고 좀 안정성 있는 프로그램을 하도록 해야 할거 같다.

저작자 표시 비영리 변경 금지
크리에이티브 커먼즈 라이선스
Creative Commons License
Trackback 0 Comment 1
2009/12/27 00:04

C#을 이용한 LPT1 포트 제어 자료 - 시작시점...


참고자료 : http://www.codeproject.com/KB/cs/control_e_appliances.aspx

1. hwinterface.ocx 를 regsvr32 를 통해서 등록한다.
2. Visual Studio 의 도구 상자에서 ocx 를 등록한다.
   - Hwinterface Control의 activex 컨트롤이 생긴다.
3. 해당 폼으로 가져와서 인스턴스를 생성한다.
4. 나머지 코드는 참고 자료의 링크에 존재 하는 파일을 참고 하기 바람

저작자 표시 비영리 변경 금지
크리에이티브 커먼즈 라이선스
Creative Commons License
Trackback 0 Comment 0
2009/12/23 13:44

MD5 샘플 코드


--선언--
using System.Security.Cryptography;

--코드--
        #region MD5 메소드
        static string getMd5Hash(string input)
        {
            // Create a new instance of the MD5CryptoServiceProvider object.
            MD5 md5Hasher = MD5.Create();

            // Convert the input string to a byte array and compute the hash.
            byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(input));

            // Create a new Stringbuilder to collect the bytes
            // and create a string.
            StringBuilder sBuilder = new StringBuilder();

            // Loop through each byte of the hashed data
            // and format each one as a hexadecimal string.
            for (int i = 0; i < data.Length; i++)
            {
                sBuilder.Append(data[i].ToString("x2"));
            }

            // Return the hexadecimal string.
            return sBuilder.ToString();
        }

        // Verify a hash against a string.
        static bool verifyMd5Hash(string input, string hash)
        {
            // Hash the input.
            string hashOfInput = getMd5Hash(input);

            // Create a StringComparer an comare the hashes.
            StringComparer comparer = StringComparer.OrdinalIgnoreCase;

            if (0 == comparer.Compare(hashOfInput, hash))
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        #endregion

        #region MD5 테스트 블록
        private void button1_Click(object sender, EventArgs e)
        {
            // 암호화 문자열을 가져온다.
            string convmd5 = getMd5Hash(textBox1.Text);

            // 암호화된 내용을 출력한다.
            textBox2.Text = convmd5;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            // 해당 문자열을 가져와서 암호화된 내용과 비교 한다.
            if (verifyMd5Hash(textBox3.Text, textBox2.Text) == true)
            {
                MessageBox.Show("맞습니다.");
            }
            else
            {
                MessageBox.Show("틀립니다.");
            }
        }
        #endregion

저작자 표시 비영리 변경 금지
크리에이티브 커먼즈 라이선스
Creative Commons License
Trackback 0 Comment 0