# 甲壳虫的Base64之旅

如下的一只甲壳虫，我们希望把它编码成 Base64，再从Base64解码出来。
![](./bug.jpg)

代码框架如下：

```python
import numpy as np
import cv2
import base64

def img_to_base64(img):
    # TODO(You):

def img_from_base64(img_base64):
    # TODO(You):

if __name__ == '__main__':
    img = cv2.imread('bug.jpg')

    img_base64 = img_to_base64(img)
    img = img_from_base64(img_base64)

    cv2.imshow('img_decode', img)
    cv2.waitKey()
    cv2.destroyAllWindows()
```

以下对两个函数实现正确的是？

## 答案

```python
def img_to_base64(img):
    return base64.b64encode(cv2.imencode('.jpg', img)[1]).decode()

def img_from_base64(img_base64):
    jpg_original = base64.b64decode(img_base64)
    jpg_as_np = np.frombuffer(jpg_original, dtype=np.uint8)
    img = cv2.imdecode(jpg_as_np, flags=1)
    return img
```

## 选项

### A

```python
def img_to_base64(img):
    return base64.b64encode(cv2.imencode('.jpg', img)[1])

def img_from_base64(img_base64):
    jpg_original = base64.b64decode(img_base64)
    img = cv2.imdecode(jpg_original, flags=1)
    return img
```

### B

```python
def img_to_base64(img):
    return base64.b64encode(cv2.imencode('.jpg', img)).decode()

def img_from_base64(img_base64):
    jpg_original = base64.b64decode(img_base64)
    jpg_as_np = np.frombuffer(jpg_original, dtype=np.uint8)
    img = cv2.imdecode(jpg_as_np, flags=1)
    return img
```

### C

```python
def img_to_base64(img):
    return base64.b64encode(cv2.imencode('.jpg', img)[1]).decode()

def img_from_base64(img_base64):
    jpg_original = base64.b64decode(img_base64)
    jpg_as_np = np.frombuffer(jpg_original)
    img = cv2.imdecode(jpg_as_np, flags=1)
    return img
```
