我正在尝试使用 libswscale 在使用 cgo 编码为 h264 之前缩放图像。这里我写了一个简单的demo(抱歉代码风格不好,我只是想快速验证一下):
func scale(img []byte, scaleFactor int) {
input, _, _ := image.Decode(bytes.NewReader(img))
if a, ok := input.(*image.YCbCr); ok {
width, height := a.Rect.Dx(), a.Rect.Dy()
var format C.enum_AVPixelFormat = C.AV_PIX_FMT_YUV420P
context := C.sws_getContext(C.int(width), C.int(height), format, C.int(width/scaleFactor), C.int(height/scaleFactor), 0, C.int(0x10), nil, nil, nil)
in := make([]uint8, 0)
in = append(in, a.Y...)
in = append(in, a.Cb...)
in = append(in, a.Cr...)
stride := []C.int{C.int(width), C.int(width / 2), C.int(width / 2), 0}
outstride := []C.int{C.int(width / scaleFactor), C.int(width / scaleFactor / 2), C.int(width / scaleFactor / 2), 0}
out := make([]uint8, width*height/scaleFactor/scaleFactor*3/2)
C.sws_scale(context, (**C.uint8_t)(unsafe.Pointer(&in[0])), (*C.int)(&stride[0]), 0,
C.int(height), (**C.uint8_t)(unsafe.Pointer(&out[0])), (*C.int)(&outstride[0]))
min := image.Point{0, 0}
max := image.Point{width / scaleFactor, height / scaleFactor}
output := image.NewYCbCr(image.Rectangle{Min: min, Max: max}, image.YCbCrSubsampleRatio420)
paneSize := width * height / scaleFactor / scaleFactor
output.Y = out[:paneSize]
output.Cb = out[paneSize : paneSize*5/4]
output.Cr = out[paneSize*5/4:]
opt := jpeg.Options{
Quality: 90,
}
f, _ := os.Create("img.jpeg")
jpeg.Encode(f, output, &opt)
}
}
每次我运行代码片段时,我都会收到一条错误消息bad dst image pointers
,说我的代码有什么问题。我是cgo的新手,所以代码对你来说可能很愚蠢,我为此道歉。如果您有更优雅的方式来实现功能,我会全力以赴。任何建议将不胜感激。