how to save image,gif and music in android studio

喜你入骨 提交于 2020-02-25 22:29:44

问题


I have tried this code,

public class PhotoEditing extends AppCompatActivity implements GetGifAdapter.GlideInterface, SdCardSongAdapter.MediaInterface
        , FiltersListFragmentListener, EmojiFragmentListener, AddTextFragmentListener {

    PhotoEditorView image_preview;
    ImageView image_gif/*,image_preview*/;
    ImageView save, back;
    LinearLayout linearLayout;
    public String sessionId;
    Uri image_selected_uri;
    FFmpeg ffmpeg;

    public Bitmap originalBitmap, filterdBitmap, finalBitmap;
    LinearLayout btn_music_list, btn_add_gif, btn_filters_list, btn_emoji, btn_add_text, btn_add_motion;
    MediaPlayer mediaPlayer;
    String mediaData;
    LinearLayout relativeLayout;
    RelativeLayout seekbar_layout, fm;
    RelativeLayout.LayoutParams layoutparam;
    RangeSeekBar rangeSeekBar;
    Runnable r;
    Handler mHandler;
    private int duration;
    private TextView tvLeft, tvRight;
    RelativeLayout rl_replace, music_fragment;
    FilterListFragment filterListFragment;
    EmojiFragment emojiFragment;
    PhotoEditor photoEditor;
    int screenWidth, screenHeight;
    Bitmap bitmap;
    int brightnessFinal = 0;
    int saturationFinal = 0;
    int constrantFinal = 0;
    int hue = 0;

    Context context = this;

    static {
        System.loadLibrary("NativeImageProcessor");
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_photo_editing);

        image_preview = findViewById(R.id.image_preview);
        image_preview.getSource().setScaleType(ImageView.ScaleType.FIT_XY);
        photoEditor = new PhotoEditor.Builder(this, image_preview)
                .setPinchTextScalable(true)
                .build();
        image_gif = findViewById(R.id.image_gif);
        linearLayout = findViewById(R.id.linearLayout);
        btn_music_list = findViewById(R.id.btn_music_list);
        btn_add_gif = findViewById(R.id.btn_add_gif);
        btn_filters_list = findViewById(R.id.btn_filters_list);
        btn_emoji = findViewById(R.id.btn_emoji);
        btn_add_text = findViewById(R.id.btn_add_text);
        fm = findViewById(R.id.frame);
        rl_replace = findViewById(R.id.replace_fragment);
        music_fragment = findViewById(R.id.music_fragment);
        seekbar_layout = findViewById(R.id.seekbar_layout);
        rangeSeekBar = findViewById(R.id.rangeSeekBar);
        rangeSeekBar.setNotifyWhileDragging(true);
        mHandler = new Handler();
        tvLeft = findViewById(R.id.tvLeft);
        tvRight = findViewById(R.id.tvRight);
        relativeLayout = findViewById(R.id.relativeLayout);
        save = findViewById(R.id.btndone);
        back = findViewById(R.id.btnhome);
        mediaPlayer = new MediaPlayer();


        sessionId = getIntent().getStringExtra("gallary");
        sessionId = getPathFromUri(PhotoEditing.this, Uri.parse(sessionId));
        image_selected_uri = Uri.parse(sessionId);
        loadImage();

        btn_music_list.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (seekbar_layout.getVisibility() == View.GONE) {
                    if (mediaPlayer != null && mediaPlayer.isPlaying()) {
                        mediaPlayer.stop();
                    }
                    MusicListFragment musicListFragment = new MusicListFragment();
                    FragmentManager fragmentManager = getSupportFragmentManager();
                    FragmentTransaction transaction = fragmentManager.beginTransaction();
                    transaction.replace(R.id.replace_fragment, musicListFragment);
                    transaction.addToBackStack(null);
                    transaction.commit();
                    seekbar_layout.setVisibility(View.VISIBLE);

                } else if (seekbar_layout.getVisibility() == View.VISIBLE) {
                    seekbar_layout.setVisibility(View.GONE);
                }
            }
        });

        btn_add_gif.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                seekbar_layout.setVisibility(View.GONE);
                GIfFragment gIfFragment = new GIfFragment();
                FragmentManager fragmentManager = getSupportFragmentManager();
                FragmentTransaction transaction = fragmentManager.beginTransaction();
                transaction.replace(R.id.replace_fragment, gIfFragment);
                transaction.addToBackStack(null);
                transaction.commit();
            }
        });


        save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                ffmpeg.execute("ffmpeg -loop 1 -i "+ image_preview + "-i "+ MeadiaData(mediaData) +" -c:v libx264 -tune stillimage -c:a aac -b:a 192k -pix_fmt yuv420p -shortest out.mp4",null);
            }
        });
    }

    private void loadImage() {
        bitmap = BitmapFactory.decodeFile(image_selected_uri.toString());
        originalBitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true);
        originalBitmap = modifyOrientation(originalBitmap, sessionId);
        finalBitmap = originalBitmap.copy(Bitmap.Config.ARGB_8888, true);
        filterdBitmap = originalBitmap.copy(Bitmap.Config.ARGB_8888, true);

        DisplayMetrics displayMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        int f3672y = displayMetrics.widthPixels;
        int f3673z = displayMetrics.heightPixels;
        float f = getResources().getDisplayMetrics().density;
        int i = f3672y - ((int) (40.0f * f));
        int i2 = f3673z - ((int) (f * 100.0f));
        image_preview.getSource().setImageBitmap(originalBitmap);
    }



    private class DownloadFilesTask extends AsyncTask<Filter, Bitmap, Bitmap> {
        ImageView imageView;
        ProgressDialog dialog;

        public DownloadFilesTask(ImageView imageView) {
            this.imageView = imageView;
            dialog = new ProgressDialog(PhotoEditing.this);
            dialog.setTitle(getResources().getString(R.string.app_name));
            dialog.setMessage("Processing Wait");
            dialog.setCancelable(false);
            dialog.show();
        }

        @Override
        protected Bitmap doInBackground(Filter... bitmaps) {
            filterdBitmap = originalBitmap.copy(Bitmap.Config.ARGB_8888, true);
            finalBitmap = bitmaps[0].processFilter(filterdBitmap);
            return finalBitmap;
        }

        protected void onPostExecute(Bitmap result) {
            imageView.setImageBitmap(result);
            image_preview.getSource().setColorFilter(ColorFilterGenerator.adjustColor(brightnessFinal, constrantFinal, saturationFinal, hue));
            dialog.dismiss();
        }
    }


    public Bitmap modifyOrientation(Bitmap bitmap, String image_absolute_path) {

        try {
            ExifInterface ei = new ExifInterface(image_absolute_path);
            int orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);

            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    return rotate(bitmap, 90);

                case ExifInterface.ORIENTATION_ROTATE_180:
                    return rotate(bitmap, 180);

                case ExifInterface.ORIENTATION_ROTATE_270:
                    return rotate(bitmap, 270);

                case ExifInterface.ORIENTATION_FLIP_HORIZONTAL:
                    return flip(bitmap, true, false);

                case ExifInterface.ORIENTATION_FLIP_VERTICAL:
                    return flip(bitmap, false, true);

                default:
                    return bitmap;
            }
        } catch (Exception e) {

        }
        return bitmap;
    }

    public static Bitmap rotate(Bitmap bitmap, float degrees) {
        Matrix matrix = new Matrix();
        matrix.postRotate(degrees);
        return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
    }

    public static Bitmap flip(Bitmap bitmap, boolean horizontal, boolean vertical) {
        Matrix matrix = new Matrix();
        matrix.preScale(horizontal ? -1 : 1, vertical ? -1 : 1);
        return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
    }

    public static String getPathFromUri(final Context context, final Uri uri) {

        final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

        if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {

            if (isExternalStorageDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }

            } else if (isDownloadsDocument(uri)) {

                final String id = DocumentsContract.getDocumentId(uri);
                final Uri contentUri = ContentUris.withAppendedId(
                        Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

                return getDataColumn(context, contentUri, null, null);
            } else if (isMediaDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }

                final String selection = "_id=?";
                final String[] selectionArgs = new String[]{
                        split[1]
                };

                return getDataColumn(context, contentUri, selection, selectionArgs);
            }
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }

        return null;
    }

    private String getTime(int seconds) {
        int hr = seconds / 3600;
        int rem = seconds % 3600;
        int mn = rem / 60;
        int sec = rem % 60;
        return String.format("%02d", hr) + ":" + String.format("%02d", mn) + ":" + String.format("%02d", sec);
    }

    @Override
    public void MeadiaData(String string) {
        mediaData = string;
        mediaPlayer = MediaPlayer.create(context, Uri.parse(string));
        mediaPlayer.start();

        mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {

            @Override
            public void onPrepared(MediaPlayer mp) {
                // TODO Auto-generated method stub
                duration = mp.getDuration() / 1000;
                tvLeft.setText("00:00:00");

                tvRight.setText(getTime(mp.getDuration() / 1000));
                mp.setLooping(true);
                rangeSeekBar.setRangeValues(0, duration);
                rangeSeekBar.setSelectedMinValue(0);
                rangeSeekBar.setSelectedMaxValue(duration);
                rangeSeekBar.setEnabled(true);
                rangeSeekBar.setOnRangeSeekBarChangeListener(new RangeSeekBar.OnRangeSeekBarChangeListener() {
                    @Override
                    public void onRangeSeekBarValuesChanged(RangeSeekBar bar, Object minValue, Object maxValue) {
                        mediaPlayer.seekTo((int) minValue * 1000);

                        tvLeft.setText(getTime((int) bar.getSelectedMinValue()));

                        tvRight.setText(getTime((int) bar.getSelectedMaxValue()));
                    }
                });
                final Handler handler = new Handler();
                handler.postDelayed(r = new Runnable() {
                    @Override
                    public void run() {
                        if (mediaPlayer.getCurrentPosition() >= rangeSeekBar.getSelectedMaxValue().intValue() * 1000)
                            mediaPlayer.seekTo(rangeSeekBar.getSelectedMinValue().intValue() * 1000);
                        handler.postDelayed(r, 1000);
                    }
                }, 1000);
            }
        });
        super.onBackPressed();
    }

    @Override
    public void GlideData(String string) {
        screenWidth = image_preview.getWidth();
        screenHeight = image_preview.getHeight();
        layoutparam = new RelativeLayout.LayoutParams(screenWidth, screenHeight);
        image_gif.setLayoutParams(layoutparam);
        image_gif.setScaleType(ImageView.ScaleType.FIT_XY);
        fm.removeView(image_gif);
        fm.addView(image_gif);

        Glide.with(context).load(string).into(image_gif);
        super.onBackPressed();
    }

}

I have one image that will be set on photo-editor-view ,one GIF that will be set on image-view and one music which i have set on range seek bar and i want to save that three in video format how i can done in android studio. I have tried lots to ideas but i could't find that solution,is there any way to solve that problem.

来源:https://stackoverflow.com/questions/60256790/how-to-save-image-gif-and-music-in-android-studio

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!