当前位置:网站首页>Andrews - multimedia programming
Andrews - multimedia programming
2022-07-07 02:46:00 【Full stack programmer webmaster】
Hello everyone , I meet you again , I'm the king of the whole stack
Multimedia concept
- writing 、 picture 、 Audio 、 video Calculate the size of the computer image Image size = Total image pixels * The size of each pixel occupies
- Monochromatic graph : Every pixel takes up 1/8 Bytes
- 16 Color map : Every pixel takes up 1/2 Bytes
- 256 Color map : Every pixel takes up 1 Bytes
- 24 Bitmap : Every pixel takes up 3 Bytes
Load large pictures into memory
Android System to ARGB Represents each pixel , So each pixel occupies 4 Bytes , very easy out of memory
Scale the image
- Get screen width and height
Display dp = getWindowManager().getDefaultDisplay();
int screenWidth = dp.getWidth();
int screenHeight = dp.getHeight();
- Get the width and height of the picture
Options opts = new Options();
// Request image attributes but not memory
opts.inJustDecodeBounds = true;
BitmapFactory.decodeFile("sdcard/dog.jpg", opts);
int imageWidth = opts.outWidth;
int imageHeight = opts.outHeight;
- Divide the width and height of the picture by the width and height of the screen , Calculate the scale of width and height , Take a larger value as the zoom ratio of the picture
int scale = 1;
int scaleX = imageWidth / screenWidth;
int scaleY = imageHeight / screenHeight;
if(scaleX >= scaleY && scaleX > 1){
scale = scaleX;
}
else if(scaleY > scaleX && scaleY > 1){
scale = scaleY;
}
- Load pictures in scale
// Set scaling
opts.inSampleSize = scale;
// Apply for memory for pictures
opts.inJustDecodeBounds = false;
Bitmap bm = BitmapFactory.decodeFile("sdcard/dog.jpg", opts);
iv.setImageBitmap(bm);
Create a copy of the picture in memory
Directly loaded bitmap Objects are only read . Unable to change . To change an image, you can only create an identical one in memory bitmap copy . Then change the copy
// Load original
Bitmap srcBm = BitmapFactory.decodeFile("sdcard/photo3.jpg");
iv_src.setImageBitmap(srcBm);
// Create a blank that is the same size as the original bitmap
Bitmap copyBm = Bitmap.createBitmap(srcBm.getWidth(), srcBm.getHeight(), srcBm.getConfig());
// Define the brush
Paint paint = new Paint();
// Lay the paper on the drawing board
Canvas canvas = new Canvas(copyBm);
// hold srcBm The content of is drawn in copyBm On
canvas.drawBitmap(srcBm, new Matrix(), paint);
iv_copy.setImageBitmap(copyBm);
Create a copy of the picture in memory Directly loaded bitmap Objects are only read . Unable to change . To change an image, you can only create an identical one in memory bitmap copy . Then change the copy
// Load original
Bitmap srcBm = BitmapFactory.decodeFile("sdcard/photo3.jpg");
iv_src.setImageBitmap(srcBm);
// Create a blank that is the same size as the original bitmap
Bitmap copyBm = Bitmap.createBitmap(srcBm.getWidth(), srcBm.getHeight(), srcBm.getConfig());
// Define the brush
Paint paint = new Paint();
// Lay the paper on the drawing board
Canvas canvas = new Canvas(copyBm);
// hold srcBm The content of is drawn in copyBm On
canvas.drawBitmap(srcBm, new Matrix(), paint);
iv_copy.setImageBitmap(copyBm);
Special effect the picture
- First define a matrix object
Matrix mt = new Matrix();
- Zoom effect
//x Axis zoom 1 times ,y Axis zoom 0.5 times
mt.setScale(1, 0.5f);
- Rotation effect
// With copyBm.getWidth() / 2, copyBm.getHeight() / 2 The point is the pivot point , Rotate in time 30 degree
mt.setRotate(30, copyBm.getWidth() / 2, copyBm.getHeight() / 2);
- translation
//x Axis coordinates +10,y Axis coordinates +20
mt.setTranslate(10, 20);
- The mirror
// hold X Coordinates become negative
mt.setScale(-1, 1);
// The picture moves to the right as a whole
mt.postTranslate(copyBm.getWidth(), 0);
- inverted reflection in water
// hold Y Coordinates become negative
mt.setScale(1, -1);
// The picture moves down as a whole
mt.postTranslate(0, copyBm.getHeight());
Sketchpad
Record user touch events XY coordinate , Draw a straight line
- to ImageView Set touch listening , Get the user's touch event , And know that the user touches ImageView Coordinates of
iv.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
switch (event.getAction()) {
// Touch the screen
case MotionEvent.ACTION_DOWN:
// Get the coordinates of your fingers when touching the screen
startX = (int) event.getX();
startY = (int) event.getY();
break;
// Slide on screen
case MotionEvent.ACTION_MOVE:
// The user slides his finger . The coordinates are constantly changing , Get the latest coordinates
int newX = (int) event.getX();
int newY = (int) event.getY();
// Use last time onTouch Draw a straight line with the coordinates obtained by the method and the coordinates obtained this time
canvas.drawLine(startX, startY, newX, newY, paint);
iv.setImageBitmap(copyBm);
startX = newX;
startY = newY;
break;
}
return true;
}
});
- Brush effect , Bold brush
paint.setStrokeWidth(8);
- palette . Change the brush color
paint.setColor(Color.GREEN);
- Save the picture to SD card
FileOutputStream fos = null;
try {
fos = new FileOutputStream(new File("sdcard/dazuo.png"));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Save the picture
copyBm.compress(CompressFormat.PNG, 100, fos);
- Every time the system receives SD When the card is ready to broadcast . Will traverse sd All files and directories of the card , Put all the multimedia files traversed in MediaStore The database holds an index . This index includes the file names of multimedia files 、 route 、 size
- Every time the gallery is opened . I won't traverse sd Card to get pictures . Instead, it is through the content provider from MediaStore Get the information of pictures in the database , Then read the picture
- Start the system or click load sd card button when , The system will send sd Card ready broadcast , We can also send ready broadcasts manually
Intent intent = new Intent();
intent.setAction(Intent.ACTION_MEDIA_MOUNTED);
intent.setData(Uri.fromFile(Environment.getExternalStorageDirectory()));
sendBroadcast(intent);
heartbeat
- principle : Overlay the photos of wearing underwear and clothes . Underwear is shown below , When the user swipes the screen . What you touch is a coat photo . Set the pixels passed by your fingers to be transparent . Underwear photos show up
iv.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_MOVE:
int newX = (int) event.getX();
int newY = (int) event.getY();
// Make the specified pixel transparent
copyBm.setPixel(newX, newY, Color.TRANSPARENT);
iv.setImageBitmap(copyBm);
break;
}
return true;
}
});
- Setting just one pixel at a time is too slow , Take the touched pixel as the center of the circle . The radius is 5 A circle , All pixels in the circle are made transparent
for (int i = -5; i < 6; i++) {
for (int j = -5; j < 6; j++) {
if(Math.sqrt(i * i + j * j) <= 5)
copyBm.setPixel(newX + i, newY + j, Color.TRANSPARENT);
}
}
Music player
Broadcast service
- The code for playing audio should be executed in the service . Define a playback service MusicService
- The definition of service is play、stop、pause、continuePlay Other methods
private void play() {
// TODO Auto-generated method stub
player.reset();
try {
player.setDataSource("sdcard/bzj.mp3");
player.prepare();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
player.start();
}
private void pause() {
player.pause();
}
private void stop() {
player.stop();
}
private void continuePlay() {
player.start();
}
- Extract these methods into an interface MusicInterface
- Define an intermediate human , Inherit Binder, Realization MusicInterface
- First start start-up MusicService, Again bind
Intent intent = new Intent(this, MusicService.class);
startService(intent);
bindService(intent, conn, BIND_AUTO_CREATE);
- Set the progress bar according to the playback progress
- Get the current playback time and the maximum time of the current audio
int currentPosition = player.getCurrentPosition();
int duration = player.getDuration();
- The playback progress needs to be obtained constantly . Keep refreshing the progress bar . Use a timer every 500 Get a playback progress in milliseconds
- Send a message to Handler. Put the playback progress into Message In the object , stay Handler In the update SeekBar Progress
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
int currentPosition = player.getCurrentPosition();
int duration = player.getDuration();
Message msg = Message.obtain();
// Save the playback progress into Message in
Bundle data = new Bundle();
data.putInt("currentPosition", currentPosition);
data.putInt("duration", duration);
msg.setData(data);
MainActivity.handler.sendMessage(msg);
}
}, 5, 500);
- stay Activity In the definition of Handler
static Handler handler = new Handler(){
public void handleMessage(android.os.Message msg) {
// Take out the data carried by the message
Bundle data = msg.getData();
int currentPosition = data.getInt("currentPosition");
int duration = data.getInt("duration");
// Set the playback schedule
sb.setMax(duration);
sb.setProgress(currentPosition);
};
};
- Drag the progress bar to change the playback progress
// to sb Set up a drag listening
sb.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
// Call when dragging stops
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
int progress = seekBar.getProgress();
mi.seekTo(progress);
}
// Call when you start dragging
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
// Call constantly when dragging
@Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
}
});
Video player
SurfaceView
- The real-time update of the picture is highly required
- Double buffering technology : There are two canvases in memory ,A Canvas display to screen ,B Canvas draws the next frame in memory . After drawing B Show to screen ,A Continue to draw the next frame in memory
- Playing video is also used MediaPlayer. It's just different from audio , To set which SurfaceView
SurfaceView sv = (SurfaceView) findViewById(R.id.sv);
SurfaceHolder sh = sv.getHolder();
MediaPlayer player = new MediaPlayer();
player.reset();
try {
player.setDataSource("sdcard/2.3gp");
player.setDisplay(sh);
player.prepare();
} catch (Exception e) {
e.printStackTrace();
}
player.start();
- SurfaceView It's a heavyweight component , Only when visible
- to SurfaceHolder Set up CallBack. Similar to listening . To know SurfaceView The state of
sh.addCallback(new Callback() {
//SurfaceView Called on destroy
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
}
//SurfaceView Call... On creation
@Override
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
}
});
- SurfaceView Once invisible . Will be destroyed , Once visible . Will be created . Stop playing when destroying . Play again when you create it again
camera
- Start the camera program provided by the system
// Implicitly start the camera provided by the system Activity
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Set the path to save photos
File file = new File(Environment.getExternalStorageDirectory(), "haha.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
startActivityForResult(intent, 0);
- Start the camera program provided by the system
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
File file = new File(Environment.getExternalStorageDirectory(), "haha.3gp");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
// Set the quality of the saved video file
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
startActivityForResult(intent, 0);
Copyright notice : This article is the original article of the blogger , Blog , Do not reprint without permission .
Publisher : Full stack programmer stack length , Reprint please indicate the source :https://javaforall.cn/116865.html Link to the original text :https://javaforall.cn
边栏推荐
- 一文读懂Faster RCNN
- Statistics of radar data in nuscenes data set
- fiddler的使用
- Unity custom webgl packaging template
- Argo workflows source code analysis
- 巴比特 | 元宇宙每日必读:IP授权是NFT的破圈之路吗?它的难点在哪里?Holder该如何选择合作平台?...
- Douban average 9 x. Five God books in the distributed field!
- Redis入门完整教程:复制原理
- [C # notes] use file stream to copy files
- MySQL
猜你喜欢
随机推荐
MySQL
Code line breaking problem of untiy text box
巴比特 | 元宇宙每日必读:IP授权是NFT的破圈之路吗?它的难点在哪里?Holder该如何选择合作平台?...
Go swagger use
数论 --- 快速幂、快速幂求逆元
fasterxml ToStringSerializerBase报错
6-6 vulnerability exploitation SSH security defense
4--新唐nuc980 挂载initramfs nfs文件系统
Qpushbutton- "function refinement"
从零安装Redis
Derivative, partial derivative, directional derivative
PCL 常用拟合模型及使用方法
Here comes a white paper to uncover the technology behind Clickhouse, a node with 10000 bytes!
Kysl Haikang camera 8247 H9 ISAPI test
MMDetection3D加载毫米波雷达数据
AWS学习笔记(一)
【Node学习笔记】chokidar模块实现文件监听
The so-called consumer Internet only matches and connects industry information, and does not change the industry itself
Mmdetection3d loads millimeter wave radar data
Application analysis of face recognition