NSImage 到 NSBitmapImageRep

2024-05-06

如何将 NSImage 转换为 NSBitmapImageRep?我有代码:

- (NSBitmapImageRep *)bitmapImageRepresentation
{
    NSBitmapImageRep *ret = (NSBitmapImageRep *)[self representations];

    if(![ret isKindOfClass:[NSBitmapImageRep class]])
    {
        ret = nil;
        for(NSBitmapImageRep *rep in [self representations])
            if([rep isKindOfClass:[NSBitmapImageRep class]])
            {
                ret = rep;
                break;
            }
    }

    if(ret == nil)
    {
        NSSize size = [self size];

        size_t width         = size.width;
        size_t height        = size.height;
        size_t bitsPerComp   = 32;
        size_t bytesPerPixel = (bitsPerComp / CHAR_BIT) * 4;
        size_t bytesPerRow   = bytesPerPixel * width;
        size_t totalBytes    = height * bytesPerRow;

        NSMutableData *data = [NSMutableData dataWithBytesNoCopy:calloc(totalBytes, 1) length:totalBytes freeWhenDone:YES];

        CGColorSpaceRef space = CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB);

        CGContextRef ctx = CGBitmapContextCreate([data mutableBytes], width, height, bitsPerComp, bytesPerRow, CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB), kCGBitmapFloatComponents | kCGImageAlphaPremultipliedLast);

        if(ctx != NULL)
        {
            [NSGraphicsContext saveGraphicsState];
            [NSGraphicsContext setCurrentContext:[NSGraphicsContext graphicsContextWithGraphicsPort:ctx flipped:[self isFlipped]]];

            [self drawAtPoint:NSZeroPoint fromRect:NSZeroRect operation:NSCompositeCopy fraction:1.0];

            [NSGraphicsContext restoreGraphicsState];

            CGImageRef img = CGBitmapContextCreateImage(ctx);

            ret = [[NSBitmapImageRep alloc] initWithCGImage:img];
            [self addRepresentation:ret];

            CFRelease(img);
            CFRelease(space);

            CGContextRelease(ctx);
        }
    }


    return ret;
}

它可以工作,但会导致内存泄漏。至少当我将它与 ARC 一起使用时是这样。使用initWithData:[nsimagename TIFFRepresentation]它无法正常工作。有些图像的表现效果不好。我认为这取决于图像的格式和色彩空间。还有其他方法可以实现这一目标吗?


结果与mrwalker建议的解决方案:

Original image:
enter image description here

Converted to bitmapimagerep and back to image 1 time:
enter image description here

Converted to bitmapimagerep and back to image 3 times:
enter image description here

如您所见,转换为 NSBitmapImageRep 后图像每次都会变暗


@Julius:您的代码太复杂并且包含多个错误。我将仅对第一行进行更正:

- (NSBitmapImageRep *)bitmapImageRepresentation
{
   for( NSImageRep *rep in [self representations] )
      if( [rep isKindOfClass:[NSBitmapImageRep class]] ) return rep;
   return nil;
}

这将提取第一个NSBitmapImageRep如果它是表示中的成员,或者将返回 nil,如果没有NSBitmapImageRep。我会给你另一个解决方案,它总是有效的NSImageReps在陈述中:NSBitmapImageRep, NSPDFImageRep or NSCGImageSnapshotRep or ...

- (NSBitmapImageRep *)bitmapImageRepresentation
{
   CGImageRef CGImage = [self CGImageForProposedRect:nil context:nil hints:nil];
   return [[[NSBitmapImageRep alloc] initWithCGImage:CGImage] autorelease];
}

或者为了避免 NSImage 的子类化,您可以编写:

NSImage *img = [[[NSImage alloc] initWithContentsOfFile:filename] autorelease];
CGImageRef CGImage = [img CGImageForProposedRect:nil context:nil hints:nil];
NSBitmapImageRep *rep = [[[NSBitmapImageRep alloc] initWithCGImage:CGImage] autorelease];

这只会返回一个NSBitmapImageRep如果图像包含多个表示(例如,很多NSBitmapImageRep来自 TIFF 文件)。但添加一些代码很简单。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

NSImage 到 NSBitmapImageRep 的相关文章

随机推荐

  • Flex 字典字面量

    在 Flex 中工作 我需要用相当复杂的结构填充字典 基于本文档页面 http livedocs adobe com flex 3 html help html content 10 Lists of data 4 html我尝试通过以下语
  • RequestDispatcher.forward 到媒体文件?

    我最近有一个需要解决的问题 https stackoverflow com questions 19385223 how to transparently stream a file to the browser并找到了一个解决方案 但如果
  • setShadowLayer Android API 差异

    我为我的应用程序开发了一个自定义视图组件 并且正在努力向圆圈添加阴影 这是我的类扩展 View 的代码 public class ChartView extends View public ChartView Context context
  • 第一个字母改为大写

    是否有其他版本可以使每个字符串的第一个字母大写 并且对于 flac perl 也使用 FALSE name lt hallo gsub alpha U 1 name perl TRUE 你可以尝试这样的事情 name lt hallo pa
  • 封闭实例的匿名类

    我正在阅读 Joshua Bloch 的 Effective Java 第二版 目前我在第 22 项 它描述了内部类和嵌套类 但我无法理解他这句话的意思 匿名类具有封闭实例当且仅当它们发生时 在非静态上下文中 有人能给我一个代码示例并解释它
  • UINavigationController:iPad 上正在呈现视图控制器,同时关闭另一个控制器

    我有一个需要用户登录的视图 当用户尝试打开该视图但他尚未登录时 我将调用登录视图供他登录 完成后我将调用他想要的原始视图查看 在 iPhone 上 当我将视图控制器推到那里时 这工作得很好 但在我展示视图控制器的 iPad 上 这不起作用
  • Runtime.getRuntime().exec(),执行Java类

    我正在从我的应用程序内部执行 Java 类 proc Runtime getRuntime exec java Test 我怎样才能识别是否Test执行成功与否 即没有例外 重定向输出 错误 proc Runtime getRuntime
  • 使用 Swift 的无大小写枚举而不是实际情况是否有技术原因?

    作为 Swift 新手 我发现 enum HttpMethod static let post POST static let get GET can assign to string property request httpMethod
  • 在视口中保留绝对定位的元素(jquery)

    我现在正在开发一个带有很多工具提示的网站 我想确保工具提示始终完全显示在视口中 我知道有工具提示插件 但它们对我不起作用 因为工具提示是通过 css 完成的 而且我不能全部更改 任何想要获得工具提示的元素都会被赋予一个position re
  • 如何在 Python Paramiko 中配置 ssh StrictHostKeyChecking=no 的等效项

    我正在使用 Paramiko 通过 Python 脚本进行 sshing 我的ssh命令如下 ssh A o strictHostKeyChecking no
  • delphi分组框标题颜色变化

    我正在使用 BDS 2006 想知道您是否可以使用项目中存在的 XPmanifest 更改组框和单选按钮组标题的颜色 因为它始终是蓝色 唯一的方法是重写 Paint 方法TGroupBox http docwiki embarcadero
  • Python 中的延迟求值/惰性求值

    我想延迟对类实例的成员函数的调用的评估 直到该实例实际存在 最小工作示例 class TestClass def init self variable 0 self variable 0 variable 0 def get variabl
  • 使用 PHP 的 HTML 中的选项字段

    我想根据从下拉列表中选择的区域名称搜索员工列表 我可以将数据库中的区域名称检索到 PHP HTML 的下拉列表中 但现在我很困惑如何将下拉列表中的选定选项传递给 PHP 中的 SQL 查询 我还想要索引号 选定的选项 我的代码如下
  • 私有静态方法有必要吗?

    原理工程师 https stackoverflow com users 201787 metal在我上一家公司有一条规则private static方法应该作为实现文件中的函数实现 而不是作为类方法 我不记得他的规则是否有任何例外 我在目前
  • 使用 PyODBC 选择表中的列名

    我正在编写一个 Python 程序 该程序使用 PyODBC 从 Microsoft Access mdb 文件中选择一些数据 我需要发现几个不同表的列名 在 SQL Server 中 这可以通过使用类似的查询来完成 SELECT c na
  • 从 Java 读取 /dev/input/js0

    我正在尝试阅读 dev input js0来自Java 但我不断得到 java io IOException Invalid argument at java io FileInputStream read0 Native Method a
  • Symfony 2 Dom Crawler:如何在 Element 中仅获取 text()

    使用 Dom Crawler 仅获取文本 无标签 html EOT lt lt lt div class coucu Get Description span Coucu span div EOT crawler new Crawler h
  • UrlMappings 将 URL 指向 Grails 中的资产管道文件

    在 Grails 3 0 中 如何将 URL 映射到assets folder 例如 http localhost 8080 favicon ico gt grails app assets images bookmark ico 我尝试了
  • 如何从已安装的云端硬盘文件夹中永久删除?

    我编写了一个脚本 在每次迭代后将我的模型和训练示例上传到 Google Drive 以防发生崩溃或任何阻止笔记本运行的情况 如下所示 drive path drive My Drive Colab Notebooks models if p
  • NSImage 到 NSBitmapImageRep

    如何将 NSImage 转换为 NSBitmapImageRep 我有代码 NSBitmapImageRep bitmapImageRepresentation NSBitmapImageRep ret NSBitmapImageRep s