(imgSvc ImgService, fileCache FileCache, file *files.FileInfo, previewSize PreviewSize)
| 111 | } |
| 112 | |
| 113 | func createPreview(imgSvc ImgService, fileCache FileCache, |
| 114 | file *files.FileInfo, previewSize PreviewSize) ([]byte, error) { |
| 115 | fd, err := file.Fs.Open(file.Path) |
| 116 | if err != nil { |
| 117 | return nil, err |
| 118 | } |
| 119 | defer fd.Close() |
| 120 | |
| 121 | var ( |
| 122 | width int |
| 123 | height int |
| 124 | options []img.Option |
| 125 | ) |
| 126 | |
| 127 | switch previewSize { |
| 128 | case PreviewSizeBig: |
| 129 | width = 1080 |
| 130 | height = 1080 |
| 131 | options = append(options, img.WithMode(img.ResizeModeFit), img.WithQuality(img.QualityMedium)) |
| 132 | case PreviewSizeThumb: |
| 133 | width = 256 |
| 134 | height = 256 |
| 135 | options = append(options, img.WithMode(img.ResizeModeFill), img.WithQuality(img.QualityLow), img.WithFormat(img.FormatJpeg)) |
| 136 | default: |
| 137 | return nil, img.ErrUnsupportedFormat |
| 138 | } |
| 139 | |
| 140 | buf := &bytes.Buffer{} |
| 141 | if err := imgSvc.Resize(context.Background(), fd, width, height, buf, options...); err != nil { |
| 142 | return nil, err |
| 143 | } |
| 144 | |
| 145 | go func() { |
| 146 | cacheKey := previewCacheKey(file, previewSize) |
| 147 | if err := fileCache.Store(context.Background(), cacheKey, buf.Bytes()); err != nil { |
| 148 | fmt.Printf("failed to cache resized image: %v", err) |
| 149 | } |
| 150 | }() |
| 151 | |
| 152 | return buf.Bytes(), nil |
| 153 | } |
| 154 | |
| 155 | func previewCacheKey(f *files.FileInfo, previewSize PreviewSize) string { |
| 156 | return fmt.Sprintf("%x%x%x", f.RealPath(), f.ModTime.Unix(), previewSize) |
no test coverage detected