package tech.starwin.network.tools;

import android.graphics.Bitmap;

import java.io.IOException;


import okhttp3.MediaType;
import okhttp3.RequestBody;
import okio.BufferedSink;

/**
 * Created by SiKang on 2019/4/22.
 */
public class BitmapRequestBody extends RequestBody {
    private Bitmap bitmap;
    private Bitmap.CompressFormat format;

    public BitmapRequestBody(Bitmap bitmap, Bitmap.CompressFormat format) {
        this.bitmap = bitmap;
        this.format = format;
    }

    @Override
    public MediaType contentType() {
        if (format == Bitmap.CompressFormat.JPEG) {
            return MediaType.parse("image/jpeg");
        } else if (format == Bitmap.CompressFormat.PNG) {
            return MediaType.parse("image/png");
        } else if (format == Bitmap.CompressFormat.WEBP) {
            return MediaType.parse("image/webp");
        }

        return null;
    }

    @Override
    public void writeTo(BufferedSink sink) throws IOException {
        bitmap.compress(format, 100, sink.outputStream());
    }
}
