<!--
{
  "availability" : [
    "Swift: 6.3.0 -",
    "Xcode: 26.4.0 -",
    "iOS: 14.0.0 -",
    "iPadOS: 14.0.0 -",
    "macCatalyst: 14.0.0 -",
    "macOS: 11.0.0 -",
    "swift: 6.0.0 -",
    "tvOS: 14.0.0 -",
    "visionOS: -",
    "watchOS: 7.0.0 -"
  ],
  "documentType" : "symbol",
  "framework" : "Testing",
  "identifier" : "/documentation/Testing/AttachableAsImage/withUnsafeBytes(as:_:)",
  "metadataVersion" : "0.1.0",
  "role" : "Instance Method",
  "symbol" : {
    "kind" : "Instance Method",
    "modules" : [
      "Swift Testing"
    ],
    "preciseIdentifier" : "s:7Testing17AttachableAsImageP15withUnsafeBytes2as_qd__AA0bD6FormatV_qd__SWKXEtKlF"
  },
  "title" : "withUnsafeBytes(as:_:)"
}
-->

# withUnsafeBytes(as:_:)

Encode a representation of this image in a given image format.

```
borrowing func withUnsafeBytes<R>(as imageFormat: AttachableImageFormat, _ body: (UnsafeRawBufferPointer) throws -> R) throws -> R
```

## Parameters

`imageFormat`

The image format to use when encoding this image.

`body`

A function to call. A temporary buffer containing a data
representation of this instance is passed to it.

## Return Value

Whatever is returned by `body`.

## Discussion> Throws: Whatever is thrown by `body`, or any error that prevented the
> creation of the buffer.

The testing library uses this function when saving an image as an
attachment. The implementation should use `imageFormat` to determine what
encoder to use.

---

Copyright &copy; 2026 Apple Inc. All rights reserved. | [Terms of Use](https://www.apple.com/legal/internet-services/terms/site.html) | [Privacy Policy](https://www.apple.com/privacy/privacy-policy)