1 /* 2 * Copyright (C) 2013 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.android.gallery3d.jpegstream; 18 19 import java.nio.ByteOrder; 20 21 public class StreamUtils { 22 StreamUtils()23 private StreamUtils() { 24 } 25 26 /** 27 * Copies the input byte array into the output int array with the given 28 * endianness. If input is not a multiple of 4, ignores the last 1-3 bytes 29 * and returns true. 30 */ byteToIntArray(int[] output, byte[] input, ByteOrder endianness)31 public static boolean byteToIntArray(int[] output, byte[] input, ByteOrder endianness) { 32 int length = input.length - (input.length % 4); 33 if (output.length * 4 < length) { 34 throw new ArrayIndexOutOfBoundsException("Output array is too short to hold input"); 35 } 36 if (endianness == ByteOrder.BIG_ENDIAN) { 37 for (int i = 0, j = 0; i < output.length; i++, j += 4) { 38 output[i] = ((input[j] & 0xFF) << 24) | ((input[j + 1] & 0xFF) << 16) 39 | ((input[j + 2] & 0xFF) << 8) | ((input[j + 3] & 0xFF)); 40 } 41 } else { 42 for (int i = 0, j = 0; i < output.length; i++, j += 4) { 43 output[i] = ((input[j + 3] & 0xFF) << 24) | ((input[j + 2] & 0xFF) << 16) 44 | ((input[j + 1] & 0xFF) << 8) | ((input[j] & 0xFF)); 45 } 46 } 47 return input.length % 4 != 0; 48 } 49 byteToIntArray(byte[] input, ByteOrder endianness)50 public static int[] byteToIntArray(byte[] input, ByteOrder endianness) { 51 int[] output = new int[input.length / 4]; 52 byteToIntArray(output, input, endianness); 53 return output; 54 } 55 56 /** 57 * Uses native endianness. 58 */ byteToIntArray(byte[] input)59 public static int[] byteToIntArray(byte[] input) { 60 return byteToIntArray(input, ByteOrder.nativeOrder()); 61 } 62 63 /** 64 * Returns the number of bytes in a pixel for a given format defined in 65 * JpegConfig. 66 */ pixelSize(int format)67 public static int pixelSize(int format) { 68 switch (format) { 69 case JpegConfig.FORMAT_ABGR: 70 case JpegConfig.FORMAT_RGBA: 71 return 4; 72 case JpegConfig.FORMAT_RGB: 73 return 3; 74 case JpegConfig.FORMAT_GRAYSCALE: 75 return 1; 76 default: 77 return -1; 78 } 79 } 80 } 81