視頻編輯的時候掂林,為了顯示主體內容的突出,一般是在背景中加上模糊背景并且降暗度坝橡。類似這種效果
用opengl要怎樣去實現呢泻帮,那么需要這幾步去分解
1、根據視頻的顯示比例计寇,如果1:1,4:3,16:9,3:4,9:16這樣的比例去計算背景顯示大小锣杂,圖片顯示大小。
比如顯示1:1的視頻饲常,如果圖片是9:16的蹲堂,那么根據背景大小狼讨,讓圖片進行居中顯示:
具體代碼如下:
public void adjustImageScaling(int width, int height) {
float outputWidth = width;
float outputHeight = height;
if (mBitmap != null) {
int framewidth = mBitmap.getWidth();
int frameheight = mBitmap.getHeight();
int rotation = (matrixAngle + bitmapAngle) % 360;
if ((rotation == 90 || rotation == 270)) {
framewidth = mBitmap.getHeight();
frameheight = mBitmap.getWidth();
}
float ratio1 = outputWidth / framewidth;
float ratio2 = outputHeight / frameheight;
float ratioMax = Math.min(ratio1, ratio2);
// 居中后圖片顯示的大小
int imageWidthNew = Math.round(framewidth * ratioMax);
int imageHeightNew = Math.round(frameheight * ratioMax);
Log.i(TAG, "outputWidth:" + outputWidth + ",outputHeight:" + outputHeight + ",imageWidthNew:" + imageWidthNew + ",imageHeightNew:" + imageHeightNew);
// 圖片被拉伸的比例,以及顯示比例時的偏移量
float ratioWidth = outputWidth / imageWidthNew;
float ratioHeight = outputHeight / imageHeightNew;
Log.i(TAG, "isDoRotate:" + isDoRotate + ",ratioWidth:" + ratioWidth + ",ratioHeight:" + ratioHeight);
// 根據拉伸比例還原頂點
cube = new float[]{
pos[0] / ratioWidth, pos[1] / ratioHeight,
pos[2] / ratioWidth, pos[3] / ratioHeight,
pos[4] / ratioWidth, pos[5] / ratioHeight,
pos[6] / ratioWidth, pos[7] / ratioHeight,
};
mVerBuffer.clear();
mVerBuffer.put(cube).position(0);
}
}
2贝淤、對圖片、視頻幀進行模糊政供、暗化操作
模糊算法用的是高斯模糊播聪,只是說自己遍歷操作在java跑,用cpu跑邏輯布隔,計算完之后再用gpu進行渲染离陶,比起直接用opengl中遍歷,就相對快了一點衅檀。然后背景的頂點位置是填充整個顯示比例的招刨,模糊的算法借鑒如下:
我只是在里面重新添加了暗度降低的算法:
const vec4 K = vec4(1.0, 2.0 / 3.0, 1.0 / 3.0, 3.0);
vec3 p = abs(fract(c.xxx + K.xyz) * 6.0 - K.www);
return c.z * mix(K.xxx, clamp(p - K.xxx, 0.0, 1.0), c.y);
}
vec3 rgb2hsv(vec3 c) {
const vec4 K = vec4(0.0, -1.0 / 3.0, 2.0 / 3.0, -1.0);
vec4 p = mix(vec4(c.bg, K.wz), vec4(c.gb, K.xy), step(c.b, c.g));
vec4 q = mix(vec4(p.xyw, c.r), vec4(c.r, p.yzx), step(p.x, c.r));
float d = q.x - min(q.w, q.y);
return vec3(abs(q.z + (q.w - q.y) / (6.0 * d + 0.001)), d / (q.x + 0.001), q.x);
}
vec3 a = rgb2hsv(color);
vec3 m = a-vec3(0.0f, 0.0f, 0.04f);
gl_FragColor = vec4(hsv2rgb(m), orAlpha);
3、顯示原始的圖片和幀哀军,按照第一步計算的頂點繪畫該圖片
整體調用如下:
//黑色背景
GLES20.glViewport(0, 0, ConstantMediaSize.currentScreenWidth, ConstantMediaSize.currentScreenHeight);
GLES20.glClearColor(0, 0, 0, 1.0f);
GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);
//顯示區(qū)背景
GLES20.glViewport(0, 0, ConstantMediaSize.showViewWidth, ConstantMediaSize.showViewHeight);
if (currentMediaItem == null) {
return;
}
int cornor = currentMediaItem.getRotation();
imageBackgroundFilter.setmBitmap(currentMediaItem.getFirstFrame(), cornor);
imageBackgroundFilter.initTexture();
imageBackgroundFilter.onSizeChanged(mWidth, mHeight);
imageBackgroundFilter.drawBackgrondPrepare();
EasyGlUtils.bindFrameTexture(fFrame[0], fTexture[0]);
imageBackgroundFilter.drawBackground();
EasyGlUtils.unBindFrameBuffer();```