Skip to content

Instantly share code, notes, and snippets.

@NightlyNexus
Created February 27, 2017 20:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NightlyNexus/76f484fc2f08abf93b9196323252f6cc to your computer and use it in GitHub Desktop.
Save NightlyNexus/76f484fc2f08abf93b9196323252f6cc to your computer and use it in GitHub Desktop.
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import java.io.IOException;
import okhttp3.Interceptor;
import okhttp3.Response;
import okio.Buffer;
import okio.BufferedSource;
final class AsciiArtInterceptor implements Interceptor {
private static String convertToAscii(Buffer buffer, int targetWidth, int targetHeight) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeStream(buffer.clone().inputStream(), null, options);
int decodedWidth = options.outWidth;
if (decodedWidth == -1) {
return null;
}
int decodedHeight = options.outHeight;
int scaleFactor = Math.min(decodedWidth / targetWidth, decodedHeight / targetHeight);
options.inJustDecodeBounds = false;
options.inSampleSize = scaleFactor;
Bitmap image = BitmapFactory.decodeStream(buffer.clone().inputStream(), null, options);
int imageHeight = image.getHeight();
int imageWidth = image.getWidth();
if (imageHeight == 0 || imageWidth == 0) {
return "";
}
StringBuilder builder = new StringBuilder(imageHeight * imageWidth + imageHeight - 1);
for (int i = 0; i != imageHeight; i++) {
if (i != 0) {
builder.append('\n');
}
for (int j = 0; j != imageWidth; j++) {
int pixel = image.getPixel(j, i);
double value =
(((Color.red(pixel) * 0.30) + (Color.blue(pixel) * 0.59) + (Color.green(pixel)
* 0.11)));
builder.append(strChar(value));
}
}
return builder.toString();
}
private static char strChar(double g) {
if (g >= 240) {
return ' ';
}
if (g >= 210) {
return '.';
}
if (g >= 190) {
return '*';
}
if (g >= 170) {
return '+';
}
if (g >= 120) {
return '^';
}
if (g >= 110) {
return '&';
}
if (g >= 80) {
return '8';
}
if (g >= 60) {
return '#';
}
return '@';
}
@Override public Response intercept(Chain chain) throws IOException {
Response response = chain.proceed(chain.request());
BufferedSource source = response.body().source();
source.request(Long.MAX_VALUE);
android.util.Log.d("Image (" + response.request().url() + ")",
String.valueOf(convertToAscii(source.buffer(), 50, 50)));
return response;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment