12
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

画像をアスキーアートに変換(swift実装)

Last updated at Posted at 2014-06-05

スズキswiftを実装したときのメモ
UIImage(width:100px程度)を入力すると、コンソールにアスキーで出力します。

https://twitter.com/shimy_net/status/473749061053333504
swiftart.png

Objective-c
- (void)printAsciiArt:(UIImage*)image
{
    CGImageRef cgImage = [image CGImage];
    CGDataProviderRef dataProvider = CGImageGetDataProvider(cgImage);
    CFDataRef data = CGDataProviderCopyData(dataProvider);
    CFMutableDataRef mData = CFDataCreateMutableCopy(0, 0, data);
    UInt8 *pixels = (UInt8*)CFDataGetBytePtr(mData);
    
    for ( int y = 0; y < image.size.height; y = y+2 )
    {
        NSString *str = @"";
        for ( int x = 0; x < image.size.width; x++ )
        {
            UInt8 *buf = pixels + y * CGImageGetBytesPerRow(cgImage) + x * 4;
            UInt8 r = *( buf + 0 );
            UInt8 g = *( buf + 1 );
            UInt8 b = *( buf + 2 );
//            UInt8 a = *( buf + 3 );
            UInt8 l = ( r + g + b ) / 3.0;
            NSString *chr;
            if ( l <= 51 )
            {
                chr = @"@";
            }
            else if ( l > 51 && l <= 102 )
            {
                chr = @"#";
            }
            else if ( l > 102 && l <= 153 )
            {
                chr = @"=";
            }
            else if ( l > 153 && l <= 204 )
            {
                chr = @"-";
            }
            else if ( l > 204 && l <= 255 )
            {
                chr = @".";
            }
            str = [NSString stringWithFormat:@"%@%@", chr, str];
        }
        printf("%s\n", [str UTF8String]);
    }
    
    CFRelease(data);
    CFRelease(mData);
}
12
13
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?