草庐IT

ios - 通过文件URL远程获取图片文件尺寸

coder 2024-01-12 原文

我正在使用 Dropbox Core API,但在寻找获取图像文件尺寸的方法时遇到了困难。我在设备上检索缩略图,但我需要知道图像的宽度和高度才能处理对它们的修改。

而且我绝对不想在手机上下载整个文件来检查其尺寸。你想过什么技巧来得到它们吗?我在元数据中唯一拥有的是文件大小,这对我来说毫无用处。

非常感谢。

最佳答案

我想出了我的答案。我使用 UIImage 类别而不是通过 URL 下载部分文件。一旦它获得足够的数据来定义大小,它就会停止下载。

我做了一些测试,它下载了大约 30 kB 来获取图片的尺寸,无论文件大小是 300 kB 还是 10 MB,这都非常快。

它可以用于任何图像文件,而不仅仅是 Dropbox API。

这是类别的标题:

#import <UIKit/UIKit.h>

typedef void (^UIImageSizeRequestCompleted) (NSURL* imgURL, CGSize size);

@interface UIImage (RemoteSize)

+ (void) requestSizeFor: (NSURL*) imgURL completion: (UIImageSizeRequestCompleted) completion;

@end

这是源文件:

#import "UIImage+RemoteSize.h"
#import <objc/runtime.h>`

#import <objc/runtime.h>

static char *kSizeRequestDataKey = "NSURL.sizeRequestData";
static char *kSizeRequestTypeKey = "NSURL.sizeRequestType";
static char *kSizeRequestCompletionKey = "NSURL.sizeRequestCompletion";

typedef uint32_t dword;

@interface NSURL (RemoteSize)

@property (nonatomic, strong) NSMutableData* sizeRequestData;
@property (nonatomic, strong) NSString* sizeRequestType;
@property (nonatomic, copy) UIImageSizeRequestCompleted sizeRequestCompletion;

@end

@implementation NSURL (RemoteSize)

- (void) setSizeRequestCompletion: (UIImageSizeRequestCompleted) block {
objc_setAssociatedObject(self, &kSizeRequestCompletionKey, block, OBJC_ASSOCIATION_COPY);
}

- (UIImageSizeRequestCompleted) sizeRequestCompletion {
return objc_getAssociatedObject(self, &kSizeRequestCompletionKey);
}

- (void) setSizeRequestData:(NSMutableData *)sizeRequestData {
objc_setAssociatedObject(self, &kSizeRequestDataKey, sizeRequestData, OBJC_ASSOCIATION_RETAIN);
}

- (NSMutableData*) sizeRequestData {
return objc_getAssociatedObject(self, &kSizeRequestDataKey);
}

- (void) setSizeRequestType:(NSString *)sizeRequestType {
objc_setAssociatedObject(self, &kSizeRequestTypeKey, sizeRequestType, OBJC_ASSOCIATION_RETAIN);
}

- (NSString*) sizeRequestType {
return objc_getAssociatedObject(self, &kSizeRequestTypeKey);
}

#pragma mark - NSURLConnectionDelegate

- (void) connection: (NSURLConnection*) connection didReceiveResponse:(NSURLResponse *)response {
[self.sizeRequestData setLength: 0];    //Redirected => reset data
}

- (void) connection: (NSURLConnection*) connection didReceiveData:(NSData *)data {
NSMutableData* receivedData = self.sizeRequestData;

if( !receivedData ) {
    receivedData = [NSMutableData data];
    self.sizeRequestData = receivedData;
}

[receivedData appendData: data];

//Parse metadata
const unsigned char* cString = [receivedData bytes];
const NSInteger length = [receivedData length];
const char pngSignature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
const char bmpSignature[2] = {66, 77};
const char gifSignature[2] = {71, 73};
const char jpgSignature[2] = {255, 216};

if(!self.sizeRequestType ) {
    if( memcmp(pngSignature, cString, 8) == 0 ) {
        self.sizeRequestType = @"PNG";
    }
    else if( memcmp(bmpSignature, cString, 2) == 0 ) {
        self.sizeRequestType = @"BMP";
    }
    else if( memcmp(jpgSignature, cString, 2) == 0 ) {
        self.sizeRequestType = @"JPG";
    }
    else if( memcmp(gifSignature, cString, 2) == 0 ) {
        self.sizeRequestType = @"GIF";
    }
}

if( [self.sizeRequestType isEqualToString: @"PNG"] ) {
    char type[5];
    int offset = 8;

    dword chunkSize = 0;
    int chunkSizeSize = sizeof(chunkSize);

    if( offset+chunkSizeSize > length )
        return;

    memcpy(&chunkSize, cString+offset, chunkSizeSize);
    chunkSize = OSSwapInt32(chunkSize);
    offset += chunkSizeSize;

    if( offset + chunkSize > length )
        return;

    memcpy(&type, cString+offset, 4); type[4]='\0';
    offset += 4;

    if( strcmp(type, "IHDR") == 0 ) {   //Should always be first
        dword width = 0, height = 0;
        memcpy(&width, cString+offset, 4);
        offset += 4;
        width = OSSwapInt32(width);

        memcpy(&height, cString+offset, 4);
        offset += 4;
        height = OSSwapInt32(height);

        if( self.sizeRequestCompletion ) {
            self.sizeRequestCompletion(self, CGSizeMake(width, height));
        }

        self.sizeRequestCompletion = nil;

        [connection cancel];
    }
}
else if( [self.sizeRequestType isEqualToString: @"BMP"] ) {
    int offset = 18;
    dword width = 0, height = 0;
    memcpy(&width, cString+offset, 4);
    offset += 4;

    memcpy(&height, cString+offset, 4);
    offset += 4;

    if( self.sizeRequestCompletion ) {
        self.sizeRequestCompletion(self, CGSizeMake(width, height));
    }

    self.sizeRequestCompletion = nil;

    [connection cancel];
}
else if( [self.sizeRequestType isEqualToString: @"JPG"] ) {
    int offset = 4;
    dword block_length = cString[offset]*256 + cString[offset+1];

    while (offset<length) {
        offset += block_length;

        if( offset >= length )
            break;
        if( cString[offset] != 0xFF )
            break;
        if( cString[offset+1] == 0xC0 ||
           cString[offset+1] == 0xC1 ||
           cString[offset+1] == 0xC2 ||
           cString[offset+1] == 0xC3 ||
           cString[offset+1] == 0xC5 ||
           cString[offset+1] == 0xC6 ||
           cString[offset+1] == 0xC7 ||
           cString[offset+1] == 0xC9 ||
           cString[offset+1] == 0xCA ||
           cString[offset+1] == 0xCB ||
           cString[offset+1] == 0xCD ||
           cString[offset+1] == 0xCE ||
           cString[offset+1] == 0xCF ) {

            dword width = 0, height = 0;

            height = cString[offset+5]*256 + cString[offset+6];
            width = cString[offset+7]*256 + cString[offset+8];

            if( self.sizeRequestCompletion ) {
                self.sizeRequestCompletion(self, CGSizeMake(width, height));
            }

            self.sizeRequestCompletion = nil;

            [connection cancel];

        }
        else {
            offset += 2;
            block_length = cString[offset]*256 + cString[offset+1];
        }

    }
}
else if( [self.sizeRequestType isEqualToString: @"GIF"] ) {
    int offset = 6;
    dword width = 0, height = 0;
    memcpy(&width, cString+offset, 2);
    offset += 2;

    memcpy(&height, cString+offset, 2);
    offset += 2;

    if( self.sizeRequestCompletion ) {
        self.sizeRequestCompletion(self, CGSizeMake(width, height));
    }

    self.sizeRequestCompletion = nil;

    [connection cancel];
}
}

- (void) connection: (NSURLConnection*) connection didFailWithError:(NSError *)error {
if( self.sizeRequestCompletion )
    self.sizeRequestCompletion(self, CGSizeZero);
}

- (NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse {
return cachedResponse;
}

- (void) connectionDidFinishLoading: (NSURLConnection *)connection {
// Basically, we failed to obtain the image size using metadata and the
// entire image was downloaded...

if(!self.sizeRequestData.length) {
    self.sizeRequestData = nil;
}
else {
    //Try parse to UIImage
    UIImage* image = [UIImage imageWithData: self.sizeRequestData];

    if( self.sizeRequestCompletion && image) {
        self.sizeRequestCompletion(self, [image size]);
        return;
    }
}

self.sizeRequestCompletion(self, CGSizeZero);
}

@end

@implementation UIImage (RemoteSize)

+ (void) requestSizeFor: (NSURL*) imgURL completion: (UIImageSizeRequestCompleted) completion {

if( [imgURL isFileURL] ) {
    //Load from file stream
}
else {
    imgURL.sizeRequestCompletion = completion;

    NSURLRequest* request = [NSURLRequest requestWithURL: imgURL];
    NSURLConnection* conn = [NSURLConnection connectionWithRequest: request delegate: imgURL];
    [conn scheduleInRunLoop: [NSRunLoop mainRunLoop] forMode: NSDefaultRunLoopMode];
    [conn start];
}
}

@end

非常感谢这篇文章对我有很大帮助: Remote image size without downloading

希望对你也有帮助。

关于ios - 通过文件URL远程获取图片文件尺寸,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23609063/

有关ios - 通过文件URL远程获取图片文件尺寸的更多相关文章

  1. ruby - 使用 RubyZip 生成 ZIP 文件时设置压缩级别 - 2

    我有一个Ruby程序,它使用rubyzip压缩XML文件的目录树。gem。我的问题是文件开始变得很重,我想提高压缩级别,因为压缩时间不是问题。我在rubyzipdocumentation中找不到一种为创建的ZIP文件指定压缩级别的方法。有人知道如何更改此设置吗?是否有另一个允许指定压缩级别的Ruby库? 最佳答案 这是我通过查看ruby​​zip内部创建的代码。level=Zlib::BEST_COMPRESSIONZip::ZipOutputStream.open(zip_file)do|zip|Dir.glob("**/*")d

  2. ruby - 其他文件中的 Rake 任务 - 2

    我试图在一个项目中使用rake,如果我把所有东西都放到Rakefile中,它会很大并且很难读取/找到东西,所以我试着将每个命名空间放在lib/rake中它自己的文件中,我添加了这个到我的rake文件的顶部:Dir['#{File.dirname(__FILE__)}/lib/rake/*.rake'].map{|f|requiref}它加载文件没问题,但没有任务。我现在只有一个.rake文件作为测试,名为“servers.rake”,它看起来像这样:namespace:serverdotask:testdoputs"test"endend所以当我运行rakeserver:testid时

  3. ruby-on-rails - 在 Rails 中将文件大小字符串转换为等效千字节 - 2

    我的目标是转换表单输入,例如“100兆字节”或“1GB”,并将其转换为我可以存储在数据库中的文件大小(以千字节为单位)。目前,我有这个:defquota_convert@regex=/([0-9]+)(.*)s/@sizes=%w{kilobytemegabytegigabyte}m=self.quota.match(@regex)if@sizes.include?m[2]eval("self.quota=#{m[1]}.#{m[2]}")endend这有效,但前提是输入是倍数(“gigabytes”,而不是“gigabyte”)并且由于使用了eval看起来疯狂不安全。所以,功能正常,

  4. ruby-on-rails - Rails 3 中的多个路由文件 - 2

    Rails2.3可以选择随时使用RouteSet#add_configuration_file添加更多路由。是否可以在Rails3项目中做同样的事情? 最佳答案 在config/application.rb中:config.paths.config.routes在Rails3.2(也可能是Rails3.1)中,使用:config.paths["config/routes"] 关于ruby-on-rails-Rails3中的多个路由文件,我们在StackOverflow上找到一个类似的问题

  5. ruby - 将差异补丁应用于字符串/文件 - 2

    对于具有离线功能的智能手机应用程序,我正在为Xml文件创建单向文本同步。我希望我的服务器将增量/差异(例如GNU差异补丁)发送到目标设备。这是计划:Time=0Server:hasversion_1ofXmlfile(~800kiB)Client:hasversion_1ofXmlfile(~800kiB)Time=1Server:hasversion_1andversion_2ofXmlfile(each~800kiB)computesdeltaoftheseversions(=patch)(~10kiB)sendspatchtoClient(~10kiBtransferred)Cl

  6. ruby - 如何将脚本文件的末尾读取为数据文件(Perl 或任何其他语言) - 2

    我正在寻找执行以下操作的正确语法(在Perl、Shell或Ruby中):#variabletoaccessthedatalinesappendedasafileEND_OF_SCRIPT_MARKERrawdatastartshereanditcontinues. 最佳答案 Perl用__DATA__做这个:#!/usr/bin/perlusestrict;usewarnings;while(){print;}__DATA__Texttoprintgoeshere 关于ruby-如何将脚

  7. ruby - 通过 rvm 升级 ruby​​gems 的问题 - 2

    尝试通过RVM将RubyGems升级到版本1.8.10并出现此错误:$rvmrubygemslatestRemovingoldRubygemsfiles...Installingrubygems-1.8.10forruby-1.9.2-p180...ERROR:Errorrunning'GEM_PATH="/Users/foo/.rvm/gems/ruby-1.9.2-p180:/Users/foo/.rvm/gems/ruby-1.9.2-p180@global:/Users/foo/.rvm/gems/ruby-1.9.2-p180:/Users/foo/.rvm/gems/rub

  8. ruby - 使用 Vim Rails,您可以创建一个新的迁移文件并一次性打开它吗? - 2

    使用带有Rails插件的vim,您可以创建一个迁移文件,然后一次性打开该文件吗?textmate也可以这样吗? 最佳答案 你可以使用rails.vim然后做类似的事情::Rgeneratemigratonadd_foo_to_bar插件将打开迁移生成的文件,这正是您想要的。我不能代表textmate。 关于ruby-使用VimRails,您可以创建一个新的迁移文件并一次性打开它吗?,我们在StackOverflow上找到一个类似的问题: https://sta

  9. ruby - 通过 erb 模板输出 ruby​​ 数组 - 2

    我正在使用puppet为ruby​​程序提供一组常量。我需要提供一组主机名,我的程序将对其进行迭代。在我之前使用的bash脚本中,我只是将它作为一个puppet变量hosts=>"host1,host2"我将其提供给bash脚本作为HOSTS=显然这对ruby​​不太适用——我需要它的格式hosts=["host1","host2"]自从phosts和putsmy_array.inspect提供输出["host1","host2"]我希望使用其中之一。不幸的是,我终其一生都无法弄清楚如何让它发挥作用。我尝试了以下各项:我发现某处他们指出我需要在函数调用前放置“function_”……这

  10. Ruby 写入和读取对象到文件 - 2

    好的,所以我的目标是轻松地将一些数据保存到磁盘以备后用。您如何简单地写入然后读取一个对象?所以如果我有一个简单的类classCattr_accessor:a,:bdefinitialize(a,b)@a,@b=a,bendend所以如果我从中非常快地制作一个objobj=C.new("foo","bar")#justgaveitsomerandomvalues然后我可以把它变成一个kindaidstring=obj.to_s#whichreturns""我终于可以将此字符串打印到文件或其他内容中。我的问题是,我该如何再次将这个id变回一个对象?我知道我可以自己挑选信息并制作一个接受该信

随机推荐